背景:基于高可用的程式設計原則,工作中的檔案上傳,檔案一般存儲在分布式檔案存儲系統上。分布式檔案存儲系統有的是購買第三方的,有的是公司自己搭建的。不管是哪一種方式,都為開發者提供了接口文檔,我們根據接口文檔中提供的接口,實作檔案上傳的功能。
一.方法參數
1.controller層中接收前端傳遞的檔案。 (@RequestParam(value = “fileName”) MultipartFile file)
2.字元串拼接,生成唯一檔案名。文中使用 /2019/2/userid/uuid 格式
二.上傳方法
1. 建立 HttpClient 的執行個體
2. 建立某種連接配接方法的執行個體,在這裡是PostMethod。在PosttMethod 的構造函數中傳入待連接配接的位址
3. 調用第一步中建立好的執行個體的 execute 方法來執行第二步中建立好的 method 執行個體
4. 讀 response
5. 釋放連接配接。無論執行方法是否成功,都必須釋放連接配接
三:執行個體
public static String doPost( byte[] fileBytes, String fileName) {
//拿到fileName拼接URL
StringBuffer sb=new StringBuffer();
final String url = sb.append(EmailGradeTask.EMAILGRADETASKUPLOADURL).append(fileName).toString();
//建立HttpClient執行個體
CloseableHttpClient httpClient = HttpClients.createDefault();
//建立post方法連接配接執行個體,在post方法中傳入待連接配接位址
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
//設定請求參數(類似html頁面中name屬性)
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.setCharset(Charset.forName("UTF-8"));
if(fileBytes!=null) {
//内容類型,用于定義網絡檔案的類型和網頁的編碼,決定檔案接收方将以什麼形式、什麼編碼讀取這個檔案
ContentType OCTEC_STREAM = ContentType.create("application/octet-stream", Charset.forName("UTF-8"));
//添加檔案
entity.addBinaryBody("file", fileBytes, OCTEC_STREAM, fileName);
}
httpPost.setEntity(entity.build());
//發起請求,并傳回請求響應
response = httpClient.execute(httpPost);
String uploadResult = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(uploadResult);
return uploadResult;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "檔案上傳錯誤";
}
總結:
HttpClient請求和我們在浏覽器上的請求一樣,一個是手動輸入url,參數。一個是用程式實作,二者在功能上一樣,并無差別。一般接口在浏覽器上可以通路,就可以通過HttpClient請求實作。HttpClient請求分為post請求,get請求。get請求中又分為帶參數的get請求和不帶參數的get請求。