一個簡單的安卓+Servlet圖片上傳例子

來源:互聯網
上載者:User

標籤:圖片上傳

       例子比較 簡單,服務端為Java Web Servlet,doPost方法中接收圖片並儲存,然後將儲存的圖片名返回給用戶端,關鍵代碼:

@SuppressWarnings("deprecation")public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");  //設定編碼          //獲得磁碟檔案條目工廠          DiskFileItemFactory factory = new DiskFileItemFactory();          //擷取檔案需要上傳到的路徑          String path = request.getRealPath("/upload");          File file=new File(path);        if(!file.exists()){        file.mkdirs();        }        factory.setRepository(new File(path));          //設定 緩衝的大小        factory.setSizeThreshold(1024*1024) ;          //檔案上傳處理          ServletFileUpload upload = new ServletFileUpload(factory);          try {              //可以上傳多個檔案              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) );//第三方提供的                      System.out.println("上傳成功:"+filename);                    response.getWriter().print(filename);//將路徑返回給用戶端                }              }                        } catch (Exception e) {          System.out.println("上傳失敗");        response.getWriter().print("上傳失敗:"+e.getMessage());        }  }

該方法同樣適用於web端即網頁圖片上傳,不是本文重點,不在講解。

用戶端關鍵代碼:

/** * 檔案上傳 *  * @param urlStr 介面路徑 * @param filePath 本地圖片路徑 * @return */public static String formUpload(String urlStr, String filePath) {String rsp = "";HttpURLConnection conn = null;String BOUNDARY = "|"; // request頭和上傳檔案內容分隔字元try {URL url = new URL(urlStr);conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setReadTimeout(30000);conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);conn.setRequestMethod("POST");conn.setRequestProperty("Connection", "Keep-Alive");conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);OutputStream out = new DataOutputStream(conn.getOutputStream());File file = new File(filePath);String filename = file.getName();String contentType = "";if (filename.endsWith(".png")) {contentType = "image/png";}if (filename.endsWith(".jpg")) {contentType = "image/jpg";}if (filename.endsWith(".gif")) {contentType = "image/gif";}if (filename.endsWith(".bmp")) {contentType = "image/bmp";}if (contentType == null || contentType.equals("")) {contentType = "application/octet-stream";}StringBuffer strBuf = new StringBuffer();strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");strBuf.append("Content-Disposition: form-data; name=\"" + filePath+ "\"; filename=\"" + filename + "\"\r\n");strBuf.append("Content-Type:" + contentType + "\r\n\r\n");out.write(strBuf.toString().getBytes());DataInputStream in = new DataInputStream(new FileInputStream(file));int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}in.close();byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();out.write(endData);out.flush();out.close();// 讀取返回資料StringBuffer buffer = new StringBuffer();BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));String line = null;while ((line = reader.readLine()) != null) {buffer.append(line).append("\n");}rsp = buffer.toString();reader.close();reader = null;} catch (Exception e) {e.printStackTrace();} finally {if (conn != null) {conn.disconnect();conn = null;}}return rsp;}

服務端圖例:


用戶端圖例:


注意:測試的時候,請在用戶端書寫完整的本機區域網路IP地址:

/** * 圖片上傳路徑 */public static final String UPLOAD_URL="http://192.168.1.188:8080/uploadImage/UploadServlet";/** * 圖片下載路徑 */public static final String DOWNLOAD_URL="http://192.168.1.188:8080/uploadImage/upload/";

源碼地址:http://download.csdn.net/detail/baiyuliang2013/8714775

一個簡單的安卓+Servlet圖片上傳例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.