先说服务器端,需要包含commons-fileupload.jar和commons-io.jar这俩jar包,注意要导入到WEB-INF/lib目录下面,否则导入不正确要吃很多亏
再看代码
package com.apptest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUpload extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //获得磁盘文件条目工厂。 DiskFileItemFactory factory = new DiskFileItemFactory(); //获取文件上传需要保存的路径,upload文件夹需存在。 String path = request.getSession().getServletContext().getRealPath("/upload"); //设置暂时存放文件的存储室,这个存储室可以和最终存储文件的文件夹不同。因为当文件很大的话会占用过多内存所以设置存储室。 factory.setRepository(new File(path)); //设置缓存的大小,当上传文件的容量超过缓存时,就放到暂时存储室。 factory.setSizeThreshold(1024*1024); //上传处理工具类(高水平API上传处理?) ServletFileUpload upload = new ServletFileUpload(factory); try{ //调用 parseRequest(request)方法 获得上传文件 FileItem 的集合list 可实现多文件上传。 List<FileItem> list = (List<FileItem>)upload.parseRequest(request); for(FileItem item:list){ //获取表单属性名字。 String name = item.getFieldName(); //如果获取的表单信息是普通的文本信息。即通过页面表单形式传递来的字符串。 if(item.isFormField()){ //获取用户具体输入的字符串, String value = item.getString(); request.setAttribute(name, value); } //如果传入的是非简单字符串,而是图片,音频,视频等二进制文件。 else{ //获取路径名 String value = item.getName(); //取到最后一个反斜杠。 int start = value.lastIndexOf("\\"); //截取上传文件的 字符串名字。+1是去掉反斜杠。 String filename = value.substring(start+1); request.setAttribute(name, filename); /*第三方提供的方法直接写到文件中。 * item.write(new File(path,filename));*/ //收到写到接收的文件中。 OutputStream out = new FileOutputStream(new File(path,filename)); InputStream in = item.getInputStream(); int length = 0; byte[] buf = new byte[1024]; System.out.println("获取文件总量的容量:"+ item.getSize()); while((length = in.read(buf))!=-1){ out.write(buf,0,length); } in.close(); out.close(); } } }catch(Exception e){ e.printStackTrace(); } } }
然后是客服端程序
MainActivity
package com.example.androidtest; import java.io.File; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener{ private static String requestURL = "http://172.19.76.105/Secret/com/FileUpload"; private Button selectImage, uploadImage; private ImageView imageView; private String picPath = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); selectImage = (Button) this.findViewById(R.id.selectImage); uploadImage = (Button) this.findViewById(R.id.uploadImage); selectImage.setOnClickListener(this); uploadImage.setOnClickListener(this); imageView = (ImageView) this.findViewById(R.id.imageView); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.selectImage: /*** * 这个是调用android内置的intent,来过滤图片文件 ,同时也可以过滤其他的 */ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, 1); break; case R.id.uploadImage: if (picPath == null) { Toast.makeText(MainActivity.this, "请选择图片!", 1000).show(); } else { final File file = new File(picPath); if (file != null) { new Thread(new Runnable(){ @Override public void run() { int request = UploadUtil.uploadFile(file, requestURL); System.out.println("upload"); //uploadImage.setText(request+""); } }).start(); } } break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { /** * 当选择的图片不为空的话,在获取到图片的途径 */ Uri uri = data.getData(); //Log.e(TAG, "uri = " + uri); try { String[] pojo = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, pojo, null, null, null); if (cursor != null) { ContentResolver cr = this.getContentResolver(); int colunm_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(colunm_index); /*** * 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了, * 这样的话,我们判断文件的后缀名 如果是图片格式的话,那么才可以 */ if (path.endsWith("jpg") || path.endsWith("png")) { picPath = path; Bitmap bitmap = BitmapFactory.decodeStream(cr .openInputStream(uri)); imageView.setImageBitmap(bitmap); } else { alert(); } } else { alert(); } } catch (Exception e) { } } super.onActivityResult(requestCode, resultCode, data); } private void alert() { Dialog dialog = new AlertDialog.Builder(this).setTitle("提示") .setMessage("您选择的不是有效的图片") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { picPath = null; } }).create(); dialog.show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ GGView.enable=false; System.exit(0); } return true; } }
UploadUtil
package com.example.androidtest; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.UUID; import android.util.Log; public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * 上传文件到服务器 * @param file 需要上传的文件 * @param RequestURL 请求的rul * @return 返回响应的内容 */ public static int uploadFile(File file, String RequestURL) { int res=0; 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); 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是文件的名字,包含后缀名 */ sb.append("Content-Disposition: form-data; name=\"file\"; 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=成功 当响应成功,获取响应的流 */ res = conn.getResponseCode(); Log.e(TAG, "response code:" + res); if (res == 200) { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); } else { Log.e(TAG, "request error"); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return res; } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="选择图片" android:id="@+id/selectImage" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="上传图片" android:id="@+id/uploadImage" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" /> </LinearLayout>