轉載: https://blog.csdn.net/lsqingfeng/article/details/90611686
我這里的需求主要是因為https頁面要訪問http,不能直接訪問,暫時加一層的方法訪問.
上傳文件先請求https,然后在https的后台訪問http
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.3</version> </dependency>
/** * 使用httpclint 發送文件 * @param url: 接口全路徑 * @param file: 上傳文件 * @param fileParamName: 接口對應文件的參數名:相當於@RequestParam("fileParamName") * @param headerParams: 請求頭信息: 可能需要攜帶token,注意不要設置content-type * @param otherParams: 其他參數 * @return */ public static String uploadApiFile(String url ,MultipartFile file,String fileParamName,Map<String,String>headerParams,Map<String,String>otherParams) { CloseableHttpClient httpClient = HttpClients.createDefault(); String result = ""; try { String fileName = file.getOriginalFilename(); HttpPost httpPost = new HttpPost(url); //添加header for (Map.Entry<String, String> e : headerParams.entrySet()) { httpPost.addHeader(e.getKey(), e.getValue()); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(Charset.forName("utf-8")); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代碼解決返回中文亂碼問題 builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流 for (Map.Entry<String, String> e : otherParams.entrySet()) { builder.addTextBody(e.getKey(), e.getValue());// 類似瀏覽器表單提交,對應input的name和value } HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost);// 執行提交 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { // 將響應內容轉換為字符串 result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
如果有大佬知道js 直接https網頁訪問http上傳文件的方式! 還望指點一二