需求: 在手機客戶端調用服務器端接口 把手機中的圖片上傳到 接口提供的服務器上。 php
例如 新浪微博中的 發表附帶圖片的微博。 java
其實能夠在客戶端模擬表單提交同樣,把圖片附件上傳到接口提供的服務器上。 apache
新浪和騰訊的微博都是這樣實現的,具體能夠參考: 編程
新浪微博接口: http://open.weibo.com/wiki/Statuses/upload
個人實現代碼以下(測試經過):
客戶端調用代碼: 數組
package com.common.myTest; import java.io.File; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; public class Hclient { public static void main(String args[]) { String targetURL = null; //-- 指定URL File targetFile = null; //-- 指定上傳文件 targetFile = new File("D:\\image1\\超大圖片.jpg"); targetURL = "http://localhost:8080/servlet/HServlets"; // servleturl PostMethod filePost = new PostMethod(targetURL); try { // 經過如下方法能夠模擬頁面參數提交 Part[] parts = { new FilePart(targetFile.getName(), targetFile) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout( 5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { System.out.println("上傳成功"); // 上傳成功 } else { System.out.println("上傳失敗"); // 上傳失敗 } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }
package com.common.myTest; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletConfig; 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; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class HServlets extends HttpServlet { private Log log = LogFactory.getLog(HServlets.class); private static final long serialVersionUID = 1L; private String uploadPath; // 上傳文件的目錄 private String tempPath; // 臨時文件目錄 File tempPathFile; public void init(ServletConfig config) throws ServletException { super.init(config); uploadPath = config.getServletContext().getInitParameter("imageStorePath"); tempPath = config.getServletContext().getInitParameter("images_120"); File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdirs(); } File tempPathFile = new File(tempPath); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } } @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { log.info("進入上傳圖片的servlt"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); // 設置緩衝區大小,這裏是4kb factory.setRepository(tempPathFile);// 設置緩衝區目錄 ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(4194304); // 設置最大文件尺寸,這裏是4MB List<FileItem> items = upload.parseRequest(request);// 獲得全部的文件 Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); log.info("上傳圖片的名字:"+fileName); if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile.getName()); fi.write(savedFile); } } log.info("上傳成功!"); } catch (Exception e) { log.info(e.getMessage()); // 能夠跳轉出錯頁面 e.printStackTrace(); } } }