背景
在java後臺將內容拼接爲字符串,然後使用RestTemplate將字符串以文件的方式上傳到指定接口
思路
使用 RestTemplate 時,將字符串封裝爲字節流,然後上傳
代碼
/**
* 將字符串以文件的方式上傳
*
* @param url 上傳的接口 url
* @param content 上傳的字符串內容
* @param fileName 文件的名稱
* @param toPath 存放在服務器上的位置
* @return RestTemplate 的請求結果
* @author daleyzou
*/
public static ResponseEntity<String> postFileData(String url, String content,String fileName, String toPath) {
RestTemplate client = new RestTemplate();
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("name", fileName);
param.add("filename", fileName);
param.add("path", toPath);
// 構建字節流數組
ByteArrayResource resource = new ByteArrayResource(content.getBytes()) {
@Override
public String getFilename() {
// 文件名
return fileName;
}
};
param.add("file", resource);
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param,headers);
return client.exchange(url,HttpMethod.POST, httpEntity, String.class);
}