適用場景:
網絡絕對路徑的URL文件或圖片,不存儲到本地,轉換成stream,直接使用HTTPClient傳送到SpringBoot的服務端,將文件存儲下來,並返回一個文件地址。目前分層架構的系統愈來愈多這種需求,因此記錄下來以備不時之需。
一、調用端
首先引入httpclient所需包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.4</version> </dependency>
調用代碼:html
package test.http; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.*; import java.net.URL; import java.nio.charset.Charset; /** * 文件傳送 * 發送文件流到服務器端 * 服務器端使用SpringBoot的MultipartFile接收 * * 適用場景: * 絕對路徑的URL文件,不存儲到本地,轉換成stream,直接使用HTTPClient傳送到SpringBoot * */ public class TestUpload { public static void main(String[] args) { //文件URL,此處取豆瓣上的一個圖片 String fileUrl ="https://img1.doubanio.com/view/photo/l/public/p2537149328.webp"; try { //提取到文件名 String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1); //轉換成文件流 InputStream is = new URL(fileUrl).openStream(); //接收文件的服務器地址 String uploadURL = "http://localhost:8003/fileupload"; //建立HttpClient CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(uploadURL); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); /*綁定文件參數,傳入文件流和contenttype,此處也能夠繼續添加其餘formdata參數*/ builder.addBinaryBody("file",is, ContentType.MULTIPART_FORM_DATA,fileName); HttpEntity entity = builder.build(); httpPost.setEntity(entity); //執行提交 HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); if(responseEntity != null){ //將響應的內容轉換成字符串 String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); //此處根據服務器返回的參數轉換,這裏返回的是JSON格式 JSONObject output = JSON.parseObject(result); JSONArray body = output.getJSONArray("body"); String resUrl = body.get(0)+""; System.out.println(resUrl); }
if(is != null){
is.close();
}
}catch (Exception ex){ ex.printStackTrace(); } } }
二、服務端java
服務端直接使用MultipartFile接收便可web
/** * 上傳文件 * * @throws BusinessException */ @PostMapping("") public String upload(@RequestParam(defaultValue = "", required = false) String prefix, @RequestParam("file") MultipartFile... files) throws BusinessException { ResultView<List<String>> resultView = new ResultView<>(); List<String> list = new ArrayList<>(); for (MultipartFile file : files) { if (file.isEmpty()) { log.warn("have empty upload file,you need check is right?"); continue; } String filepath = storageService.store(file, prefix); list.add(fileServerAddress + filepath.replaceAll("\\\\", "/")); } resultView.setBody(list); log.info(JSONObject.toJSONString(resultView)); return JSONObject.toJSONString(resultView); }
具體如何存儲如何返回,因人而異,我這裏返回的是JSON字符串。apache
其餘:本文參考了博友Vincent-Li的博文,表示感謝:json