android上传图片至服务器

本实例实现了android上传手机图片至服务器,服务器进行保存

服务器servlet代码(需要jar包有:commons-fileupload-1.2.2.jar, commons-io-2.0.1.jar, standard.jar)

         public void doGet(HttpServletRequest request, HttpServletResponse response)
                         throws ServletException, IOException {
                 try {
                         System.out.println("IP:" + request.getRemoteAddr());
                         // 1、创建工厂类:DiskFileItemFactory
                         DiskFileItemFactory facotry = new DiskFileItemFactory();
                         String tempDir = getServletContext().getRealPath("/WEB-INF/temp");
                         facotry.setRepository(new File(tempDir));//设置临时文件存放目录
                         // 2、创建核心解析类:ServletFileUpload
                         ServletFileUpload upload = new ServletFileUpload(facotry);
                         upload.setHeaderEncoding("UTF-8");// 解决上传的文件名乱码
                         upload.setFileSizeMax(1024 * 1024 * 1024);// 单个文件上传最大值是1M
                         upload.setSizeMax(2048 * 1024 * 1024);//文件上传的总大小限制
  
                         // 3、判断用户的表单提交方式是不是multipart/form-data
                         boolean bb = upload.isMultipartContent(request);
                         if (!bb) {
                                 return;
                         }
                         // 4、是:解析request对象的正文内容List<FileItem>
                         List<FileItem> items = upload.parseRequest(request);
                         String storePath = getServletContext().getRealPath(
                                         "/WEB-INF/upload");// 上传的文件的存放目录
                         for (FileItem item : items) {
                                 if (item.isFormField()) {
                                         // 5、判断是否是普通表单:打印看看
                                         String fieldName = item.getFieldName();// 请求参数名
                                         String fieldValue = item.getString("UTF-8");// 请求参数值
                                         System.out.println(fieldName + "=" + fieldValue);
                                 } else {
                                         // 6、上传表单:得到输入流,处理上传:保存到服务器的某个目录中
                                         String fileName = item.getName();// 得到上传文件的名称 C:\Documents
                                                                                                                 // and
                                                                                                                 // Settings\shc\桌面\a.txt
                                                                                                                 // a.txt
                                         //解决用户没有选择文件上传的情况
                                         if(fileName==null||fileName.trim().equals("")){
                                                 continue;
                                         }
                                         fileName = fileName
                                                         .substring(fileName.lastIndexOf("\\") + 1);
                                         String newFileName = UUIDUtil.getUUID() + "_" + fileName;
                                         System.out.println("上传的文件名是:" + fileName);
                                         InputStream in = item.getInputStream();
                                         String savePath = makeDir(storePath, fileName) + "\\"
                                                         + newFileName;
                                         OutputStream out = new FileOutputStream(savePath);
                                         byte b[] = new byte[1024];
                                         int len = -1;
                                         while ((len = in.read(b)) != -1) {
                                                 out.write(b, 0, len);
                                         }
                                         in.close();
                                         out.close();
                                         item.delete();//删除临时文件
                                 }
                         }
                 }catch(FileUploadBase.FileSizeLimitExceededException e){
                         request.setAttribute("message", "单个文件大小不能超出5M");
                         request.getRequestDispatcher("/message.jsp").forward(request,
                                         response);
                 }catch(FileUploadBase.SizeLimitExceededException e){
                         request.setAttribute("message", "总文件大小不能超出7M");
                         request.getRequestDispatcher("/message.jsp").forward(request,
                                         response);
         }catch (Exception e) {
                         e.printStackTrace();
                         request.setAttribute("message", "上传失败");
                         request.getRequestDispatcher("/message.jsp").forward(request,
                                         response);
                 }
         }
  
         // WEB-INF/upload/1/3 打散存储目录
         private String makeDir(String storePath, String fileName) {
                 int hashCode = fileName.hashCode();// 得到文件名的hashcode码
                 int dir1 = hashCode & 0xf;// 取hashCode的低4位 0~15
                 int dir2 = (hashCode & 0xf0) >> 4;// 取hashCode的高4位 0~15
                 String path = storePath + "\\" + dir1 + "\\" + dir2;
                 File file = new File(path);
                 if (!file.exists())
                         file.mkdirs();
                 return path;
         }
  
         public void doPost(HttpServletRequest request, HttpServletResponse response)
                         throws ServletException, IOException {
                 doGet(request, response);
         }

UUIDUtil代码如下

public class UUIDUtil {
         public static String getUUID(){
                 return UUID.randomUUID().toString();
         }
 }


android客户端代码(需要jar包有:apache-mime4j-0.6.jar,httpmime-4.2.1.jar)

public class PhotoUploadActivity extends Activity {
         private String newName = "image.jpg";
         private String uploadFile = "/sdcard/Photo/001.jpg";
         private String actionUrl = "http://10.0.0.144:8080/upload/servlet/UploadServlet";
         private TextView mText1;
         private TextView mText2;
         private Button mButton;
  
         @Override
         public void onCreate(Bundle savedInstanceState) {
                 super.onCreate(savedInstanceState);
                 setContentView(R.layout.photo_upload_activity);
                 mText1 = (TextView) findViewById(R.id.myText1);
                 // "文件路径:\n"+
                 mText1.setText(uploadFile);
                 mText2 = (TextView) findViewById(R.id.myText2);
                 // "上传网址:\n"+
                 mText2.setText(actionUrl);
                 /* 设置mButton的onClick事件处理 */
                 mButton = (Button) findViewById(R.id.myButton);
                 mButton.setOnClickListener(new View.OnClickListener() {
                         public void onClick(View v) {
                                 uploadFile();
                         }
                 });
         }
  
         /* 上传文件至Server的方法 */
 
         private void uploadFile() {
                 String end = "\r\n";
                 String twoHyphens = "--";
                 String boundary = "*****";
                 try {
                         URL url = new URL(actionUrl);
                         HttpURLConnection con = (HttpURLConnection) url.openConnection();
                         /* 允许Input、Output,不使用Cache */
                         con.setDoInput(true);
                         con.setDoOutput(true);
                         con.setUseCaches(false);
                         /* 设置传送的method=POST */
                         con.setRequestMethod("POST");
                         /* setRequestProperty */
                         con.setRequestProperty("Connection", "Keep-Alive");
                         con.setRequestProperty("Charset", "UTF-8");
                         con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                         /* 设置DataOutputStream */
                         DataOutputStream ds = new DataOutputStream(con.getOutputStream());
                         ds.writeBytes(twoHyphens + boundary + end);
                         ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + newName + "\"" + end);
                         ds.writeBytes(end);
                         /* 取得文件的FileInputStream */
                         FileInputStream fStream = new FileInputStream(uploadFile);
                         /* 设置每次写入1024bytes */
                         int bufferSize = 1024;
                         byte[] buffer = new byte[bufferSize];
                         int length = -1;
                         /* 从文件读取数据至缓冲区 */
                         while ((length = fStream.read(buffer)) != -1) {
                                 /* 将资料写入DataOutputStream中 */
                                 ds.write(buffer, 0, length);
                         }
                         ds.writeBytes(end);
                         ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
                         /* close streams */
                         fStream.close();
                         ds.flush();
                         /* 取得Response内容 */
                         InputStream is = con.getInputStream();
                         int ch;
                         StringBuffer b = new StringBuffer();
                         while ((ch = is.read()) != -1) {
                                 b.append((char) ch);
                         }
                         /* 将Response显示于Dialog */
                         showDialog("上传成功" + b.toString().trim());
                         /* 关闭DataOutputStream */
                         ds.close();
                 } catch (Exception e) {
                         showDialog("上传失败" + e);
                 }
         }
  
         /* 显示Dialog的method */
         private void showDialog(String mess) {
                 new AlertDialog.Builder(PhotoUploadActivity.this).setTitle("Message").setMessage(mess)
                                 .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                         public void onClick(DialogInterface dialog, int which) {
                                         }
                                 }).show();
         }
 }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值