Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Spring File Upload

    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.6k
    Comment on it

    Spring File Upload

    Spring is a framework which provides almost all types of functionality. Spring has feature to stream based file upload. Spring file upload is very easy and maintainable. Spring provides the api to upload file streams. Like java IO spring has some classes to process file streams. To let the spring framework work for you, you need some jars in your lib, put following code in maven pom.xml to fetch dependencies :

    <!-- Apache Commons FileUpload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
    
    <!-- Apache Commons IO -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    

    Spring provides the class CommonsMultipartResolver to process stream based operations.

    ApplicationContext.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-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <mvc:annotation-driven />  
    <context:component-scan base-package="org.evon.springFileUpload.controller"/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
     <bean id="multipartResolver"
         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- max upload size in bytes -->
            <property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
    
            <!-- max size of file in memory (in bytes) -->
            <property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
     </bean>
    </beans>
    

    FileUploadController.java

    package org.evon.springFileUpload.controller;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import org.apache.log4j.Logger;
    import org.fileUpload.service.FileUploadService;
    import org.fileUpload.service.UserInfoService;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.Validator;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.support.RedirectAttributes;
    
    @Controller
    public class FileUploadController implements HandlerExceptionResolver{
        private static final Logger logger = Logger.getLogger(FileUploadController.class);
        /**
         * render the File Upload Page
         * @return
         */
        @RequestMapping(value = {"/fileUpload","/fileUpload/upload" } ,method = RequestMethod.GET)
        public ModelAndView viewUploadPage() {
            ModelAndView model = new ModelAndView("FileUploadPage");
            return model;
        }
    
        /**
         * Upload file
         */
        @RequestMapping(value = "/fileUpload/upload", method = RequestMethod.POST)
        public String uploadFileHandler(BindingResult result, @RequestParam("fileName") MultipartFile fileName, Model model, RedirectAttributes redir, HttpServletRequest request, HttpSession session) {
            UserFileInfo dbFileInfo=null;
            long fileId = userFileInfo.getId();
            if (!fileName.isEmpty()) {
               try {
                String uploadFileName = fileName.getOriginalFilename();     
                    String uploadDirPath = System.getProperty("catalina.home");;
                    //if edit file then create a revision of file.
                    uploadDirPath = uploadDirPath + File.separator + uploadFileName;
    
                     // Create the file on server
                    File serverFile = new File(uploadDirPath);
            byte[] bytes = fileName.getBytes();
                    BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                    logger.info("Server File Location : " + serverFile.getAbsolutePath());
                    redir.addFlashAttribute("successMessage", "You successfully uploaded file " + uploadFileName);
                    return "redirect:/fileUpload";
                } catch (Exception e) {
                    redir.addFlashAttribute("errorMessage", "Failed to upload ");
                    e.printStackTrace();
                    return "redirect:/fileUpload";
                }
            } else {
                model.addAttribute("errorMessage", "Failed to upload because the file was empty.");
                return "/FileUploadPage";
            }
        }
    
     @Override
        public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse res, Object arg, Exception exception) {
            Map<Object, Object> model = new HashMap<Object, Object>();
            if (exception instanceof MaxUploadSizeExceededException){
                model.put("errorMessage", "The file should be less then "+
                ((MaxUploadSizeExceededException)exception).getMaxUploadSize()+" byte.");
            } else{
                model.put("errorMessage", "Unexpected error: " + exception.getMessage());
            }
            return new ModelAndView("/FileUploadPage", (Map) model);
        }   
    }
    

    FileUploadPage.jsp

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <html>
    <head>
    <title>Upload File Page</title>
    </head>
    <body>
        <form method="POST" action="/fileUpload/upload" enctype="multipart/form-data">
            File : <input type="file" name="fileName"><br />
            <input type="submit" value="Upload File">
        </form>
    </body>
    </html>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: