我正在使用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。我该怎么做呢?


当前回答

通过邮递员上传文件以及传递一些输入数据的步骤在下面的博客以及截图中进行了很好的讨论。在本博客中,api代码是用node js编写的。你可以再看一遍,看得更清楚些。

https://jksnu.blogspot.com/2021/09/how-to-create-post-request-with.html

其他回答

缺失的视觉指南

您必须首先找到几乎看不见的“文件”的浅灰色下拉菜单,这是解锁“选择文件”按钮的魔法键。

在你选择POST后,然后选择Body->form-data,然后找到File下拉菜单,然后选择File,然后才会神奇地出现choose Files按钮:

在弹簧架侧使用以下代码:

@PostMapping(value = Constant.API_INITIAL + "/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file,String jsonFileVo) {
        FileUploadVo fileUploadVo = null;
        try {
            fileUploadVo = new ObjectMapper().readValue(jsonFileVo, FileUploadVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

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

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

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

通过邮递员上传文件以及传递一些输入数据的步骤在下面的博客以及截图中进行了很好的讨论。在本博客中,api代码是用node js编写的。你可以再看一遍,看得更清楚些。

https://jksnu.blogspot.com/2021/09/how-to-create-post-request-with.html

像这样:

Body -> form-data -> select file

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

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