我正在使用Spring MVC,这是我的方法:

/**
* Upload single file using Spring Controller.
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(
            @RequestParam("name") String name,
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request,
            HttpServletResponse response) {

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            System.out.println("Server File Location=" + serverFile.getAbsolutePath());

            return null;
        } catch (Exception e) {
            return null;
        }
    }
}

我需要在邮递员和文件中传递会话id。我该怎么做呢?


当前回答

像这样:

Body -> form-data -> select file

你必须写“file”而不是“name”

你也可以从Body ->原始字段发送JSON数据。(只需粘贴JSON字符串)

其他回答

后端部分

控制器中的Rest服务将混合@RequestPart和MultipartFile来服务这种Multipart + JSON请求。

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})

@ResponseBody
public boolean yourEndpointMethod(
    @RequestPart("properties") @Valid ConnectionProperties properties,
    @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}

前端:

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
            "name": "root",
            "password": "root"                    
        })], {
            type: "application/json"
        }));

如图所示(邮差请求):

点击查看邮差请求在表单数据为文件和json

像这样:

Body -> form-data -> select file

你必须写“file”而不是“name”

你也可以从Body ->原始字段发送JSON数据。(只需粘贴JSON字符串)

如果你需要 上传文件在多个部分使用表单数据和发送json数据(Dto对象)在同一个POST请求

在控制器中获取JSON对象作为字符串,并通过添加这一行使其反序列化

ContactDto contactDto  = new ObjectMapper().readValue(yourJSONString, ContactDto.class);

发送包含json数据文件的多部分数据的方法如下,我们需要在邮递员body选项卡中设置相应json关键字段的content-type为'application/json',如下所示:

如果您使用cookie来保持会话,则可以使用拦截器将cookie从浏览器共享给邮递员。

也可以上传一个文件,你可以使用form-data标签下的正文标签邮递员,在其中,你可以提供数据在键值格式和每个键,你可以选择值文本/文件的类型。当你选择文件类型时,出现上传文件的选项。