上传工具类
activity_up_load.xml文件代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_up_load" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/userMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textMultiLine" android:hint="请输入你的说说" /> <!-- 网格布局显示图像集 --> <GridLayout android:id="@+id/showImagePanal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:columnCount="4" android:orientation="horizontal"> <ImageView android:id="@+id/imageOne" android:layout_width="80dp" android:layout_height="80dp" android:src="@mipmap/ic_launcher" android:clickable="true" /> <ImageView android:id="@+id/imageTwo" android:layout_width="80dp" android:layout_height="80dp" android:src="@mipmap/ic_launcher" android:clickable="true" /> </GridLayout> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发布" android:onClick="doSend" /> </LinearLayout>
FileUtils文件代码
package com.example.utils; import android.content.Context; import android.database.Cursor; import android.net.Uri; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * 文件操作的工具类 */ public class FileUtils { //根据Uri取出文件所在的路径 public static String getPath(Context context, Uri uri) { if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = { "_data" }; Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection,null, null, null); int column_index = cursor.getColumnIndexOrThrow("_data"); if (cursor.moveToFirst()) { return cursor.getString(column_index); } } catch (Exception e) { e.printStackTrace(); } } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } //将一个输入流转换为一个字符串 public static String formatStreamToString(InputStream stream){ if(stream!=null){ ByteArrayOutputStream out=new ByteArrayOutputStream(); byte[] bytes=new byte[1024]; int len=0; try { while((len=stream.read(bytes))!=-1){ out.write(bytes,0,len); } String str=out.toString(); out.flush(); out.close(); stream.close(); return str; } catch (IOException e) { e.printStackTrace(); } } return null; } //执行下载文件到指定位置 public static void downLoadFile(final String fromPath, final String savePath, final CallBack callBack){ if(fromPath!=null&&savePath!=null){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL(fromPath); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setConnectTimeout(20*1000); conn.connect(); InputStream input=conn.getInputStream(); File file=new File(savePath); if(!file.getParentFile().exists()) file.getParentFile().mkdirs(); OutputStream out=new FileOutputStream(file); byte[] bytes=new byte[1024]; for(int len=0;(len=input.read(bytes))!=-1;){ out.write(bytes,0,len); } out.flush(); out.close(); input.close(); callBack.success(null);//下载成功 } catch (Exception e) { e.printStackTrace(); callBack.failed(null);//下载失败 } } }).start(); } } public static boolean existsFile(String path){ if(path!=null&&path.length()>0) { File file = new File(path); if(file.exists()) return true; } return false; } }
UploadUtils上传工具类
package com.example.utils; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.UUID; /** * * 上传工具类 */ public class UploadUtils { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10*1000; //超时时间 private static final String CHARSET = "utf-8"; //设置编码 /** * android上传文件到服务器 * @param file 需要上传的文件 * @param RequestURL 请求的url * @return 返回响应的内容 */ public static String uploadFile(File file, String RequestURL){ String result = null; String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; //内容类型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); //允许输入流 conn.setDoOutput(true); //允许输出流 conn.setUseCaches(false); //不允许使用缓存 conn.setRequestMethod("POST"); //请求方式 conn.setRequestProperty("Charset", CHARSET); //设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); conn.connect(); if(file!=null){ /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while((len=is.read(bytes))!=-1){ dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 * 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); if(res==200){ InputStream input = conn.getInputStream(); StringBuffer sb1= new StringBuffer(); int ss ; while((ss=input.read())!=-1){ sb1.append((char)ss); } result = sb1.toString(); System.out.println(result); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
UpLoadActivity文件代码:
package com.example.android_web_3; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.GridLayout; import android.widget.ImageView; import android.widget.LinearLayout; import com.example.utils.BitMapUtils; import com.example.utils.FileUtils; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; public class UpLoadActivity extends Activity implements View.OnClickListener{ private ImageView image1,image2; private GridLayout showImagePanal; private EditText inMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_up_load); image1=(ImageView)findViewById(R.id.imageOne); image2=(ImageView)findViewById(R.id.imageTwo); showImagePanal=(GridLayout)findViewById(R.id.showImagePanal); inMessage=(EditText)findViewById(R.id.userMessage); image1.setOnClickListener(this); image2.setOnClickListener(this); } //点击图像,选择图片 @Override public void onClick(View v) { switch (v.getId()) { case R.id.imageOne: Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent1, 0); break; case R.id.imageTwo: Intent intent2=new Intent(); intent2.setAction(Intent.ACTION_GET_CONTENT); intent2.setType("image/*"); startActivityForResult(intent2, 1); break; default: break; } } private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); //记录已经拍摄或者选择的图像集 private List images=new ArrayList(); //接收返回的结果 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode==RESULT_OK){ switch (requestCode) { case 0: Bundle bundle = data.getExtras();//获取相机拍照后返回值 Bitmap bitmap = (Bitmap) bundle.get("data");//获取拍照图像 String fileName = "IMG_" + sdf.format(new Date()) + ".jpg"; String path = getApplicationContext().getCacheDir() .getAbsolutePath() + "/images/" + fileName; FileOutputStream b = null; File file = new File(path); if (!file.getParentFile().exists()) file.getParentFile().mkdirs();// 创建文件夹 try { b = new FileOutputStream(path); bitmap.compress(Bitmap.CompressFormat.JPEG, 60, b); b.flush(); b.close(); } catch (Exception e) { e.printStackTrace(); } Log.i("-------------", "path:" + path); images.add(path);//记录文件路径 //bitmap = BitMapUtils.getSmallBitmap(path); //image1.setImageBitmap(bitmap); break; case 1: Uri uri = data.getData();//获取选择的图片Uri String path2 = FileUtils.getPath(this, uri);//获取图片真实保存位置 images.add(path2);//记录文件路径 //Bitmap bitmap2 = BitMapUtils.getSmallBitmap(path2);//获取压缩图像 //image2.setImageBitmap(bitmap2); break; default: break; } } if(requestCode==1 || requestCode==0){ ImageView image=new ImageView(this); image.setId(images.size()+1); image.setLayoutParams(new LinearLayout.LayoutParams(80, 80)); Bitmap bitmap = BitMapUtils.getSmallBitmap(images.get(images.size()-1)+"");//获取压缩图像 image.setImageBitmap(bitmap); showImagePanal.addView(image); } } //发布 HttpURLConnection conn=null; public void doSend(View view){ Log.i("-------------", "--------start---------"); new Thread(new Runnable() { public void run() { String msg = inMessage.getText().toString(); String path="Http://10.0.2.2:8080/Web_Project/UploadImageServlet?inputMessage="+msg; try { URL url = new URL(path); String result = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成; String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setReadTimeout(25000); conn.setConnectTimeout(5000); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", "UTF-8"); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (images != null&&images.size()>0) { DataOutputStream dos = new DataOutputStream(conn .getOutputStream()); for (int i = 0; i < images.size(); i++) { File file=new File(images.get(i).toString()); Log.i("--------------------", "file"+i+"="+file.getName()); /** * 当文件不为空,把文件包装并且上传 */ StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"uimages\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=UTF-8" + LINE_END); sb.append(LINE_END); Log.i("------------", "--Header--"+sb.toString()); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); } byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); if (res == 200) { InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.i("--------------", "result : " + result); } } Log.i("-------------", "--------responseCode:---------" + conn.getResponseCode()); Log.i("-------------", "--------end---------"); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } }).start(); } }