Java代碼
- public 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();
- 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;
- }
servlet接收代碼:
Java代碼
- package com.pingan.web;
- import java.io.File;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- 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.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- import com.alibaba.fastjson.JSONObject;
- @WebServlet(description = "檔案上傳", urlPatterns = { "/FileUploadServlet" })
- public class FileUploadServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doPost(request, response);
- }
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- response.setCharacterEncoding("utf-8");
- //利用apache的common-upload上傳元件來進行 來解析擷取到的流檔案
- //把上傳來的檔案放在這裡
- String uploadPath = getServletContext().getRealPath("/upload");//擷取檔案路徑
- //檢測是不是存在上傳檔案
- // Check that we have a file upload request
- boolean isMultipart = ServletFileUpload.isMultipartContent(request);
- if(isMultipart){
- DiskFileItemFactory factory = new DiskFileItemFactory();
- //指定在記憶體中緩存資料大小,機關為byte,這裡設為1Mb
- factory.setSizeThreshold(1024*1024);
- //設定一旦檔案大小超過getSizeThreshold()的值時資料存放在硬碟的目錄
- factory.setRepository(new File("D://temp"));
- // Create a new file upload handler
- ServletFileUpload upload = new ServletFileUpload(factory);
- // 指定單個上傳檔案的最大尺寸,機關:位元組,這裡設為5Mb
- upload.setFileSizeMax(5 * 1024 * 1024);
- //指定一次上傳多個檔案的總尺寸,機關:位元組,這裡設為10Mb
- upload.setSizeMax(10 * 1024 * 1024);
- upload.setHeaderEncoding("UTF-8"); //設定編碼,因為我的jsp頁面的編碼是utf-8的
- List<FileItem> items = null;
- try {
- // 解析request請求
- items = upload.parseRequest(request);
- } catch (FileUploadException e) {
- e.printStackTrace();
- }
- if(items!=null){
- //把上傳檔案放到伺服器的這個目錄下
- if (!new File(uploadPath).isDirectory()){
- new File(uploadPath).mkdirs(); //標明上傳的目錄此處為目前目錄,沒有則建立
- }
- //解析表單項目
- // Process the uploaded items
- Iterator<FileItem> iter = items.iterator();
- while (iter.hasNext()) {
- FileItem item = iter.next();
- //如果是普通表單屬性
- if (item.isFormField()) {
- //<input type="text" name="content">
- String name = item.getFieldName();//相當于input的name屬性
- String value = item.getString();//input的value屬性
- System.out.println("屬性:"+name+" 屬性值:"+value);
- }
- //如果是上傳檔案
- else {
- //屬性名
- String fieldName = item.getFieldName();
- //上傳檔案路徑
- String fileName = item.getName();
- fileName = fileName.substring(fileName.lastIndexOf("/")+1);// 獲得上傳檔案的檔案名
- try {
- item.write(new File(uploadPath,fileName));
- } catch (Exception e) {
- e.printStackTrace();
- }
- //給請求頁面傳回響應
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("code", "0000");
- jsonObject.put("msg", "檔案上傳成功! 檔案名是:"+fileName);
- response.getWriter().println(jsonObject.toJSONString());
- }
- }
- }
- }
- }
- }
測試main方法:
Java代碼
- public static void main(String[] args) {
- HttpsFileUtils httpsUtils = new HttpsFileUtils();
- //要上傳的檔案的路徑
- String filePath = "D:/git/fastPlat/commonWeb/src/com/pingan/file/data/base64_New2.jpg";
- String postUrl = "http://localhost:8080/commonWeb/FileUploadServlet";
- Map<String,String> postParam = new HashMap<String,String>();
- postParam.put("custNo", "11122");
- File postFile = new File(filePath);
- Map<String,Object> resultMap = httpsUtils.uploadFileByHTTP(postFile,postUrl,postParam);
- System.out.println(resultMap);
- }