Spring MVC file upload example

Spring comes with MultipartResolver to handle file upload in web application. The CommonsMultipartResolver is a common MultipartResolver implementation, which use the Apache commons upload library to handle the file upload in a form. In this tutorial, it shows how to handle the file upload in Spring MVC web application.

1. File Upload Dependency

To use CommonsMultipartResolver to handle the file upload, you need to get the commons-fileupload.jar and commons-io.jar libraries.

        <!-- Spring framework --> 
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring</artifactId>
        <version>2.5.6</version>
    </dependency>

        <!-- Spring MVC framework --> 
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>2.5.6</version>
    </dependency>

        <!-- Apache Commons Upload --> 
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2.2</version>
    </dependency>

    <!-- Apache Commons Upload --> 
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>

    <!-- JSTL --> 
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.1.2</version>
    </dependency>

    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>

2. Model

Create a MultipartFile variable to store the uploaded file. Alternatively, you can use the byte[] to store it, but i more prefer to use the MultipartFile, because it can get the uploaded file detail (file name, file size …) easily.

File : FileUpload.java

package com.mkyong.common.model;
import org.springframework.web.multipart.MultipartFile;

public class FileUpload{

    MultipartFile file;
    //getter and setter methods

}

3. File Upload Controller

Extends the SimpleFormController and handle the file upload form like a normal form.

File : FileUploadController.java

package com.mkyong.common.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.mkyong.common.model.FileUpload;

public class FileUploadController extends SimpleFormController{

    public FileUploadController(){
        setCommandClass(FileUpload.class);
        setCommandName("fileUploadForm");
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request,
        HttpServletResponse response, Object command, BindException errors)
        throws Exception {

        FileUpload file = (FileUpload)command;

        MultipartFile multipartFile = file.getFile();

        String fileName="";

        if(multipartFile!=null){
            fileName = multipartFile.getOriginalFilename();
            //do whatever you want
        }

        return new ModelAndView("FileUploadSuccess","fileName",fileName);
    }
}

Note
If you are using the byte[] to store the uploaded file, you have to register the ByteArrayMultipartFileEditor class to guide Spring to handle the conversion between the multipart object and byte array.

public class FileUploadController extends SimpleFormController{
    //...
    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
    throws ServletException {

    // Convert multipart object to byte[]
    binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());

    }

4. File Upload Validation

A simple validation for the uploaded file, display the error message if the uploaded file is empty.

File : FileUploadValidator.java

package com.mkyong.common.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.mkyong.common.model.FileUpload;

public class FileUploadValidator implements Validator{

    @Override
    public boolean supports(Class clazz) {
        //just validate the FileUpload instances
        return FileUpload.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {

        FileUpload file = (FileUpload)target;

        if(file.getFile().getSize()==0){
            errors.rejectValue("file", "required.fileUpload");
        }
    }
}

File : message.properties

required.fileUpload = Please select a file!

5. View Page

The Spring’s form tag didn’t comes with any file upload tag (that’s weird). So, you have to declared the pure HTML file tag <input type=”file” /> manually. Furthermore, in the Spring’s form, define the form encoding attribute enctype=”multipart/form-data”, so that the browser will know how to handle the multipart file. In last, wrap some Spring’s form error tag to display the error message.

Warning
Remember define the enctype=”multipart/form-data” attribute in the Spring’s form, else the file upload process will not work properly.

File : FileUploadForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
    color: #ff0000;
}

.errorblock {
    color: #000;
    background-color: #ffEEEE;
    border: 3px solid #ff0000;
    padding: 8px;
    margin: 16px;
}
</style>
</head>

<body>
    <h2>Spring MVC file upload example</h2>

    <form:form method="POST" commandName="fileUploadForm"
        enctype="multipart/form-data">

        <form:errors path="*" cssClass="errorblock" element="div" />

        Please select a file to upload : <input type="file" name="file" />
        <input type="submit" value="upload" />
        <span><form:errors path="file" cssClass="error" />
        </span>

    </form:form>

</body>
</html>
If the file is uploaded successfully, display the uploaded file name.

###File : `FileUploadSuccess.jsp`
##6. Spring Configuration
Register “`CommonsMultipartResolver`” to tell Spring to use commons-upload library to handle the file upload form. The rest is just normal bean declaration.

7. Demo

URL : http://localhost:8080/SpringMVCForm/fileupload.htm

Render a file upload component.

SpringMVC-FileUpload-Example1
Display the error message if user didn’t select a file to upload while clicking on the upload button.

SpringMVC-FileUpload-Error-Example
If file upload successful, display the uploaded file name.

SpringMVC-FileUploaded-Example-2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值