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


当前回答

在看到所有的答案后,我感到困惑,我找不到任何合适的截图来带来内容类型列。过了一段时间,我自己找到了它。希望这能帮助到像我这样的人。

以下是步骤:

点击邮递员的红色标记区域。 现在检查绿色标记的选项(Content Type)。 现在改变搜索内容类型,在黄色标记的区域。

在我的例子中:

Invoice_id_ls (key)包含json数据。 文档包含文件数据。 Placed_amount包含普通文本字符串。

其他回答

我需要传递两个:一个文件和一个整数。我是这样做的:

需要传递一个文件来上传: 按照Sumit的回答做了。 请求类型:POST Body -> form-data 在KEY标题下,输入变量的名称(后端代码中的'file')。 在后端: File = request.files[' File '] 在“文件”旁边,有一个下拉框,允许你在“文件”或“文本”之间进行选择。选择“File”,在VALUE标题下,出现了“Select files”。点击这个,打开一个窗口选择文件。

2. 需要传递一个整数:

去:

参数个数

在KEY下输入变量名(例如:id),在value下输入变量值(例如:1)

在后端:

id = request.args.get('id')

成功了!

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

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

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

Body > binary >选择文件

在[SHOW COLUMNS]中选择[Content Type],然后将“application/json”的Content - Type设置为json text参数。

像这样:

Body -> form-data -> select file

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

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