How to send multipart files and form data together to Spring controller

74 views Asked by At

In a form there are many text fields and four multpart file and I have to send both together to the spring controller. Please sugget how it can be done in spring 3.x.

I am new to spring framework and did not find anyway. All the example I found is of Springboot not for the Spring 3.x

1

There are 1 answers

2
SANTOSH KUMAR On

For sending multipart files and form data together to spring controller you can use below code snippet :

In 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>

and in your controller you can receive data something like this :

@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;
}

You can go through this example : file upload

Another way to do this is something like this click here