一个简单的安卓+Servlet图片上传例子

78 篇文章 1 订阅

 例子比较 简单,服务端为Java Web Servlet,doPost方法中接收图片并保存,然后将保存的图片名返回给客户端,关键代码:

[html]  view plain  copy
  1. @SuppressWarnings("deprecation")  
  2.     public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {  
  3.         request.setCharacterEncoding("utf-8");  //设置编码    
  4.         //获得磁盘文件条目工厂    
  5.         DiskFileItemFactory factory = new DiskFileItemFactory();    
  6.         //获取文件需要上传到的路径    
  7.         String path = request.getRealPath("/upload");    
  8.         File file=new File(path);  
  9.         if(!file.exists()){  
  10.             file.mkdirs();  
  11.         }  
  12.         factory.setRepository(new File(path));    
  13.         //设置 缓存的大小  
  14.         factory.setSizeThreshold(1024*1024) ;    
  15.         //文件上传处理    
  16.         ServletFileUpload upload = new ServletFileUpload(factory);    
  17.         try {    
  18.             //可以上传多个文件    
  19.             List<FileItem> list = (List<FileItem>)upload.parseRequest(request);    
  20.             for(FileItem item : list){    
  21.                 //获取属性名字    
  22.                 String name = item.getFieldName();    
  23.                 //如果获取的 表单信息是普通的 文本 信息    
  24.                 if(item.isFormField()){                       
  25.                     //获取用户具体输入的字符串,因为表单提交过来的是 字符串类型的    
  26.                     String value = item.getString() ;    
  27.                     request.setAttribute(name, value);    
  28.                 }else{    
  29.                     //获取路径名    
  30.                     String value = item.getName() ;    
  31.                     //索引到最后一个反斜杠    
  32.                     int start = value.lastIndexOf("\\");    
  33.                     //截取 上传文件的 字符串名字,加1是 去掉反斜杠,    
  34.                     String filename = value.substring(start+1);    
  35.                     request.setAttribute(name, filename);    
  36.                     //写到磁盘上    
  37.                     item.write( new File(path,filename) );//第三方提供的    
  38.                     System.out.println("上传成功:"+filename);  
  39.                     response.getWriter().print(filename);//将路径返回给客户端  
  40.                 }    
  41.             }    
  42.                 
  43.         } catch (Exception e) {    
  44.             System.out.println("上传失败");  
  45.             response.getWriter().print("上传失败:"+e.getMessage());  
  46.         }    
  47.           
  48.     }  

该方法同样适用于web端即网页图片上传,不是本文重点,不在讲解。

客户端关键代码:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.      * 文件上传  
  3.      *   
  4.      * @param urlStr 接口路径  
  5.      * @param filePath 本地图片路径  
  6.      * @return  
  7.      */  
  8.     public static String formUpload(String urlStr, String filePath) {  
  9.         String rsp = "";  
  10.         HttpURLConnection conn = null;  
  11.         String BOUNDARY = "|"; // request头和上传文件内容分隔符  
  12.         try {  
  13.             URL url = new URL(urlStr);  
  14.             conn = (HttpURLConnection) url.openConnection();  
  15.             conn.setConnectTimeout(5000);  
  16.             conn.setReadTimeout(30000);  
  17.             conn.setDoOutput(true);  
  18.             conn.setDoInput(true);  
  19.             conn.setUseCaches(false);  
  20.             conn.setRequestMethod("POST");  
  21.             conn.setRequestProperty("Connection", "Keep-Alive");  
  22.             conn.setRequestProperty("User-Agent",  
  23.                     "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");  
  24.             conn.setRequestProperty("Content-Type",  
  25.                     "multipart/form-data; boundary=" + BOUNDARY);  
  26.   
  27.             OutputStream out = new DataOutputStream(conn.getOutputStream());  
  28.             File file = new File(filePath);  
  29.             String filename = file.getName();  
  30.             String contentType = "";  
  31.             if (filename.endsWith(".png")) {  
  32.                 contentType = "image/png";  
  33.             }  
  34.             if (filename.endsWith(".jpg")) {  
  35.                 contentType = "image/jpg";  
  36.             }  
  37.             if (filename.endsWith(".gif")) {  
  38.                 contentType = "image/gif";  
  39.             }  
  40.             if (filename.endsWith(".bmp")) {  
  41.                 contentType = "image/bmp";  
  42.             }  
  43.             if (contentType == null || contentType.equals("")) {  
  44.                 contentType = "application/octet-stream";  
  45.             }  
  46.             StringBuffer strBuf = new StringBuffer();  
  47.             strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");  
  48.             strBuf.append("Content-Disposition: form-data; name=\"" + filePath  
  49.                     + "\"; filename=\"" + filename + "\"\r\n");  
  50.             strBuf.append("Content-Type:" + contentType + "\r\n\r\n");  
  51.             out.write(strBuf.toString().getBytes());  
  52.             DataInputStream in = new DataInputStream(new FileInputStream(file));  
  53.             int bytes = 0;  
  54.             byte[] bufferOut = new byte[1024];  
  55.             while ((bytes = in.read(bufferOut)) != -1) {  
  56.                 out.write(bufferOut, 0, bytes);  
  57.             }  
  58.             in.close();  
  59.             byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
  60.             out.write(endData);  
  61.             out.flush();  
  62.             out.close();  
  63.   
  64.             // 读取返回数据  
  65.             StringBuffer buffer = new StringBuffer();  
  66.             BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));  
  67.             String line = null;  
  68.             while ((line = reader.readLine()) != null) {  
  69.                 buffer.append(line).append("\n");  
  70.             }  
  71.             rsp = buffer.toString();  
  72.             reader.close();  
  73.             reader = null;  
  74.         } catch (Exception e) {  
  75.             e.printStackTrace();  
  76.         } finally {  
  77.             if (conn != null) {  
  78.                 conn.disconnect();  
  79.                 conn = null;  
  80.             }  
  81.         }  
  82.         return rsp;  
  83.     }  

服务端图例:


客户端图例:


注意:测试的时候,请在客户端书写完整的本机局域网IP地址:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.      * 图片上传路径  
  3.      */  
  4.     public static final String UPLOAD_URL="http://192.168.1.188:8080/uploadImage/UploadServlet";  
  5.       
  6.     /**  
  7.      * 图片下载路径  
  8.      */  
  9.     public static final String DOWNLOAD_URL="http://192.168.1.188:8080/uploadImage/upload/";  

源码地址:http://download.csdn.net/detail/baiyuliang2013/8714775
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值