Spring MVC 如何将多部分文件和表单数据一起发送到Spring控制器

mu0hgdu0  于 6个月前  发布在  Spring
关注(0)|答案(1)|浏览(66)

在一个表单中有许多文本字段和四个多部分文件,我必须将两者一起发送到spring控制器。请sugget如何在spring 3.x中完成。
我是spring框架的新手,无论如何都没有找到。我找到的所有示例都是Springboot的,而不是Spring 3.x的。

ffdz8vbo

ffdz8vbo1#

要将多部分文件和表单数据一起发送到spring控制器,您可以使用以下代码片段:
在JSP中:

<form method="POST" action="uploadMultipleFile" enctype="multipart/form-data">
    File1 to upload: <input type="file" name="file"><br /> 
    Name1: <input type="text" name="name"><br /> <br /> 
    File2 to upload: <input type="file" name="file"><br /> 
    Name2: <input type="text" name="name"><br /> <br />
    <input type="submit" value="Upload"> Press here to upload the file!
</form>

字符串
在你的控制器里你可以接收到这样的数据:

@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
public @ResponseBody
String uploadMultipleFileHandler(@RequestParam("name") String[] names,
        @RequestParam("file") MultipartFile[] files) {

    if (files.length != names.length)
        return "Mandatory information missing";

    String message = "";
    for (int i = 0; i < files.length; i++) {
        MultipartFile file = files[i];
        String name = names[i];
        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();

            logger.info("Server File Location="
                    + serverFile.getAbsolutePath());

            message = message + "You successfully uploaded file=" + name
                    + "<br />";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    }
    return message;
}


你可以通过这个例子:file upload
另一种方法是这样的click here

相关问题