我正在使用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 > binary >选择文件

其他回答

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

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

如果您想发出PUT请求,只需将所有事情都作为POST请求进行,但将_method => PUT添加到您的form-data参数中。

后端部分

控制器中的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

将字段名添加为数组

不要给出任何标题。 将json数据放在.json文件中。 选择你的两个文件,一个是.txt文件,另一个是.json文件 用于您的请求参数键。