restTemplate发送multipartFile和String混合参数及接收

最近有个任务是将文件上传到服务器后再发送到另一台服务器接收,作为一个代码表述为主的程序员,文字表达能力有限,就上代码吧~~

前端代码片段

<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, // 上传formdata封装的数据包
        dataType: 'JSON',
        processData: false,// jQuery不要去处理发送的数据
        contentType: false, // jQuery不要去设置Content-Type请求头
        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);

    //设置请求体,注意是LinkedMultiValueMap
    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);
}

你可能感兴趣的:(java,javascript,ajax)