Java使用HttpClient上傳檔案
阿新 • • 發佈:2019-01-01
上傳所用httpclient版本為4.5.1
客戶端:
/** * 模擬表單上傳檔案 * postFile 上傳的檔案 * postUrl 請求地址 * postParam 其他表單的請求引數 */ public static Map<String,Object> uploadFileByHTTP(File postFile,String postUrl,Map<String,String> postParam){ 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().setCharset(Charset.forName("UTF-8")).setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 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); //發起請求 並返回請求的響應 CloseableHttpResponse response = httpClient.execute(httpPost); try { //列印響應狀態 resultMap.put("statusCode", response.getStatusLine().getStatusCode()); //獲取響應物件 HttpEntity resEntity = response.getEntity(); if (resEntity != null) { //列印響應長度 //列印響應內容 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(); } } return resultMap; }
服務端:
/** * 將request中的檔案儲存 * @param request * @return 檔名對應檔案路徑的map */ @Override public Map<String, String> fileUpload(HttpServletRequest request) throws IllegalStateException, IOException { Map<String, String> map = new HashMap<String, String>(); // 將當前上下文初始化給 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); // 檢查form中是否有enctype="multipart/form-data" if (multipartResolver.isMultipart(request)) { // 將request變成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; // 獲取multiRequest 中所有的檔名 Iterator<String> iter = multiRequest.getFileNames(); // 定義絕對路徑 String localPath = "c:\\upfile"; File path = new File(localPath); // 資料夾不存在 則建立資料夾 if (!path.exists()) { path.mkdir(); } while (iter.hasNext()) { // 一次遍歷所有檔案 MultipartFile file = multiRequest.getFile(iter.next().toString()); if (file != null) { // 名稱生成規則 當前時間戳_隨機數_檔名 Random random = new Random(); int rand = random.nextInt(100); String filepath = localPath + new Date().getTime() + "_" + rand + "_" + file.getOriginalFilename(); // 上傳 file.transferTo(new File(filepath)); // 檔案資料儲存起來 map.put(file.getOriginalFilename(), filepath); } } } return map; }