maven
新的maven和先前的版本的API不同
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.3</version> </dependency>
上傳
package uploadTest; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UploadTest { public static Map<String,Object> uploadFileByHTTP(File postFile,String postUrl,Map<String,String> postParam){ Logger log = LoggerFactory.getLogger(UploadTest.class); Map<String,Object> resultMap = new HashMap<String,Object>(); CloseableHttpClient httpClient = HttpClients.createDefault(); try{ //把一個普通參數和文件上傳給下面這個地址 是一個servlet HttpPost httpPost = new HttpPost(postUrl); //把文件轉換成流對象FileBody FileBody fundFileBin = new FileBody(postFile); //設置傳輸參數 MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.addPart(postFile.getName(), fundFileBin);//相當於<input type="file" name="media"/> //設計文件以外的參數 Set<String> keySet = postParam.keySet(); for (String key : keySet) { //相當於<input type="text" name="name" value=name> multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("text/plain", Consts.UTF_8))); } HttpEntity reqEntity = multipartEntity.build(); httpPost.setEntity(reqEntity); log.info("發起請求的頁面地址 " + httpPost.getRequestLine()); //發起請求 並返回請求的響應 CloseableHttpResponse response = httpClient.execute(httpPost); try { log.info("----------------------------------------"); //打印響應狀態 //log.info(response.getStatusLine()); resultMap.put("statusCode", response.getStatusLine().getStatusCode()); //獲取響應對象 HttpEntity resEntity = response.getEntity(); if (resEntity != null) { //打印響應長度 log.info("Response content length: " + resEntity.getContentLength()); //打印響應內容 resultMap.put("data", EntityUtils.toString(resEntity,Charset.forName("UTF-8"))); } //銷毀 EntityUtils.consume(resEntity); } catch (Exception e) { e.printStackTrace(); } finally { response.close(); } } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } finally{ try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } log.info("uploadFileByHTTP result:"+resultMap); return resultMap; } //測試 public static void main(String args[]) throws Exception { //要上傳的文件的路徑 String filePath = "d:/test0.jpg"; String postUrl = "http://localhost:8080/v1/contract/addContract.do"; Map<String,String> postParam = new HashMap<String,String>(); postParam.put("shopId", "15"); File postFile = new File(filePath); Map<String,Object> resultMap = uploadFileByHTTP(postFile,postUrl,postParam); System.out.println(resultMap); } }
接收
@Path("addContract.do") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_HTML) public String addContract(@Context HttpServletRequest request, @Context HttpServletResponse response){ try{ //這里根據業務做修改 Contract contract = new Contract(); //重點是調用saveFile方法 UploadResult uploadResult = saveFile(request); contract.setShopId(Integer.valueOf(uploadResult.getParamMap().get("shopId"))); contract.setContractUrl(uploadResult.getFilePath()); Boolean success = contractService.addContract(contract); return JSON.toJSONString(RespApi.buildResp(200, "success", success)); } catch (ContractExeption contractExeption) { log.warn(ExceptionUtils.getStackTrace(contractExeption)); return JSON.toJSONString(RespApi.buildResp(400, "fail to add contract", false)); } } public UploadResult saveFile(HttpServletRequest request) { Map<String,String> resultMap = new HashMap<>(); String fileName = ""; try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); //如果沒以下兩行設置的話,上傳大的 文件 會占用 很多內存, //設置暫時存放的 存儲室 , 這個存儲室,可以和 最終存儲文件 的目錄不同 /** * 原理 它是先存到 暫時存儲室,然后在真正寫到 對應目錄的硬盤上, * 按理來說 當上傳一個文件時,其實是上傳了兩份,第一個是以 .tem 格式的 * 然后再將其真正寫到 對應目錄的硬盤上 */ //這個tempDir需要自己設置 File tempF = new File(tempDir); if (!tempF.exists()) { tempF.mkdirs(); } factory.setRepository(tempF); //設置 緩存的大小,當上傳文件的容量超過該緩存時,直接放到 暫時存儲室 factory.setSizeThreshold(1024 * 1024); //高水平的API文件上傳處理 ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } if (items != null) { Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); //屬性字段 if (item.isFormField()) { //獲取表單的屬性名字 String name = item.getFieldName(); String value = item.getString(); resultMap.put(name,value); } //文件 if (!item.isFormField() && item.getSize() > 0) { //可以得到流 InputStream in = item.getInputStream(); fileName = processFileName(item.getName()); try { String basePath = getRootPath(); String types = "pic"; String date = DateUtil.getNowDateStr(DateUtil.TO_DAY); String realPath = basePath + File.separator + types + File.separator + date + File.separator; //String realPath = basePath + File.separator + types + File.separator + date // + File.separator; System.out.println(realPath); File file1 = new File(realPath); if (!file1.exists()) { file1.mkdirs(); } String name = UUID.randomUUID().toString() + ".jpg"; fileName = types + File.separator + date + File.separator + name; File files = new File(realPath + name); item.write(files); } catch (Exception e) { e.printStackTrace(); } } } } } } catch (Exception e) { } UploadResult uploadResult = new UploadResult(); uploadResult.setFilePath(fileName); uploadResult.setParamMap(resultMap); return uploadResult; } //返回結果的包裝類 public class UploadResult { private String filePath; private Map<String,String> paramMap; public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public Map<String, String> getParamMap() { return paramMap; } public void setParamMap(Map<String, String> paramMap) { this.paramMap = paramMap; } }