Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Upload Progress Bar with Spring?

I have the following RestController for uploading files into my server side.

    @RequestMapping(value="/upload", method=RequestMethod.POST )
    @CrossOrigin
    public SimpleHttpResponse uploadFile(@RequestParam("uploadItem") MultipartFile fileUpload )
    {
        System.out.println(fileUpload.getOriginalFilename());
        try {
            byte[] fileBytes = fileUpload.getBytes();
            Files.write(Paths.get("C:\\Users\\" + fileUpload.getOriginalFilename()), fileBytes);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

        return new SimpleHttpResponse(true);
    }

Is there anyway to track the bytes received at any given moment and expose it to the UI ? Lot of the examples I see on Google are using Servlets/JSPs with Apache Commons. Is there a Spring based solution to get the progress or way to integrate Apache Commons File Upload with Spring ? Ideally, there would be a way to identify multiple file uploads from different users(or even from same user). Thanks for any pointers.

like image 983
Pepria Avatar asked Mar 08 '17 03:03

Pepria


1 Answers

Complete spring based solution using jquery form plugin

JSP PAGE

<!DOCTYPE html>
<html>
    <head>
        <title>File Upload</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
        <script src="http://malsup.github.com/jquery.form.js"></script>

        <script type="text/javascript">
            $(function() {

                var bar = $('.bar');
                var percent = $('.percent');
                var status = $('#status');

                $('form').ajaxForm({
                    beforeSend: function() {
                        status.empty();
                        var percentVal = '0%';
                        bar.width(percentVal);
                        percent.html(percentVal);
                    },
                    uploadProgress: function(event, position, total, percentComplete) {
                        var percentVal = percentComplete + '%';
                        bar.width(percentVal);
                        percent.html(percentVal);
                    },
                    complete: function(xhr) {
                        status.html(xhr.responseText);
                    }
                });
            });
        </script>
    </head>
    <body>
        <div class="progress">
            <div class="bar"></div >
            <div class="percent">0%</div >
        </div>

        <div id="status"></div>
        <form action="/multipartfileupload/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="file"><br>
            <input type="submit" value="Upload File to Server">
        </form>
    </body>
</html>

FileuploadController

/**
 * @author asif.hossain
 * @since 3/8/17.
 */
@Controller
@RequestMapping("/upload")
public class FileUploadController {
    @RequestMapping(method = RequestMethod.GET)
    String show() {
        return "upload";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String uploadFile(@RequestParam("file") MultipartFile file) {

        System.out.println(file.getName());
        return "home";
    }
}

ServletConfig

mvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:component-scan base-package="net.asifhossain.multipartfileupload"/>
    <bean id="viewresolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <multipart-config>
            <max-file-size>20848820</max-file-size>
            <max-request-size>418018841</max-request-size>
            <file-size-threshold>1048576</file-size-threshold>
        </multipart-config>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

You can find the working code in my github repository. Ping me if you have any issue.

https://github.com/mirmdasif/springmvc/tree/master/springmvcmultipartfileupload

like image 147
mirmdasif Avatar answered Oct 13 '22 22:10

mirmdasif