最近有个任务是将文件上传到服务器后再发送到另一台服务器接收,作为一个代码表述为主的程序员,文字表达能力有限,就上代码吧~~
前端代码片段
<table>
<tbody>
<tr>
<td>需要上传服务器的文件</td>
<td>
<input type="file" id="file0001">
</td>
</tr>
</tbody>
</table>
<div class="button-container">
<input type="submit" value="上传" @click="uploadMiniIO">
</div>
uploadMiniIO: function () {
var that = this;
var formData = new FormData();
formData.append("structureFile", document.getElementById('file0001').files[0]);
formData.append("structureFileType", "proj");
$.ajax({
url: epmsServerUrl + '/history-pms-project-transfer/upload-structure-file',
type: 'POST',
data: formData,
dataType: 'JSON',
processData: false,
contentType: false,
success: function (data) {
that.info = data.data;
}
})
}
后台接收端代码
@PostMapping("/upload-structure-file")
public Result uploadFileByFileId(@RequestPart("structureFile") MultipartFile multipartFile, String structureFileType){
Map<String, Object> map = new HashMap<>();
map.put("structureFileType", structureFileType);
return restTemplateUtils.postForMiniIO(pmsminiioUploadStructureFiles, multipartFile, map);
}
public Result postForMiniIO(String url, MultipartFile multipartFile, Map<String, Object> reqMap) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
ByteArrayResource byteArrayResource = null;
try {
byteArrayResource = new ByteArrayResource(multipartFile.getBytes()) {
@Override
public long contentLength() {
return multipartFile.getSize();
}
@Override
public String getFilename() {
return multipartFile.getOriginalFilename();
}
};
} catch (IOException e) {
Result.error(-1, "上传文件失败,文件二进制获取失败");
}
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("structureFile", byteArrayResource);
form.setAll(reqMap);
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
return restTemplate.postForObject(url, files, Result.class);
}
@PostMapping("/upload-structure-file")
public Result uploadFileByFileId(@RequestPart("structureFile") MultipartFile multipartFile, String structureFileType){
Map<String, Object> map = new HashMap<>();
map.put("structureFileType", structureFileType);
map.put("structureFile", multipartFile);
}