Upload and View Image File Spring Mvc
File Uploading is a very mutual task in whatever web application. Nosotros have earlier seen how to upload files in Servlet and Struts2 File Uploading. Today we volition learn about Spring File upload, specifically Leap MVC File Upload for single and multiple files.
Bound MVC File Upload
Spring MVC framework provides support for uploading files by integrating Apache Eatables FileUpload API. The process to upload files is very easy and requires simple configurations. Nosotros volition create a simple Bound MVC project in STS that will look like beneath prototype.
Most of the function is the banality-plate code generated by STS tool, we will focus on the changes that are required to utilize Spring file upload integration.
Maven Dependencies for Apache Commons FileUpload
First of all, we need to add Apache Commons FileUpload dependencies in our pom.xml file, then that required jar files are part of the web application. Beneath is the dependency snippet from my pom.xml file.
<!-- Apache Commons FileUpload --> <dependency> <groupId>eatables-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>i.iii.1</version> </dependency> <!-- Apache Commons IO --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>ii.four</version> </dependency> Spring File Upload Form Views
We will create ii JSP pages to allow single and multiple file uploads in jump spider web application.
upload.jsp view code:
<%@ taglib uri="https://java.dominicus.com/jsp/jstl/core" prefix="c" %> <%@ page session="faux" %> <html> <caput> <title>Upload File Asking Page</title> </head> <body> <form method="Postal service" activeness="uploadFile" enctype="multipart/grade-information"> File to upload: <input blazon="file" proper noun="file"><br /> Name: <input type="text" name="proper noun"><br /> <br /> <input type="submit" value="Upload"> Press here to upload the file! </course> </trunk> </html> uploadMultiple.jsp view code:
<%@ taglib uri="https://coffee.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="fake" %> <html> <head> <title>Upload Multiple File Asking Folio</championship> </head> <body> <form method="POST" activity="uploadMultipleFile" enctype="multipart/form-data"> File1 to upload: <input type="file" name="file"><br /> Name1: <input blazon="text" name="proper noun"><br /> <br /> File2 to upload: <input type="file" proper noun="file"><br /> Name2: <input blazon="text" name="name"><br /> <br /> <input blazon="submit" value="Upload"> Printing hither to upload the file! </grade> </body> </html> Find that these files are elementary HTML files, I am non using any JSP or Leap tags to avoid complexity. The of import point to note is that form enctype should be multipart/grade-information, then that Spring spider web application knows that the asking contains file information that needs to be processed.
Likewise note that for multiple files, the course field "file" and "name" are the same in the input fields, so that the data volition exist sent in the form of an assortment. We will have the input array and parse the file data and store information technology in the given file name.
Bound MVC Multipart Configuration
To utilise Apache Commons FileUpload for handling multipart requests, all we demand to practise is configure multipartResolver bean with class as org.springframework.web.multipart.commons.CommonsMultipartResolver.
Our concluding Leap configuration file looks similar beneath.
servlet-context.xml code:
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="https://www.springframework.org/schema/mvc" xmlns:xsi="https://world wide web.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans" xmlns:context="https://www.springframework.org/schema/context" xsi:schemaLocation="https://www.springframework.org/schema/mvc https://world wide web.springframework.org/schema/mvc/spring-mvc.xsd https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- DispatcherServlet Context: defines this servlet's asking-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP Become requests for /resource/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/**" location="/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resource in the /Web-INF/views directory --> <beans:bean class="org.springframework.spider web.servlet.view.InternalResourceViewResolver"> <beans:belongings name="prefix" value="/WEB-INF/views/" /> <beans:belongings name="suffix" value=".jsp" /> </beans:bean> <beans:bean id="multipartResolver" class="org.springframework.web.multipart.eatables.CommonsMultipartResolver"> <!-- setting maximum upload size --> <beans:property name="maxUploadSize" value="100000" /> </beans:edible bean> <context:component-browse base-parcel="com.journaldev.spring.controller" /> </beans:beans> Find that I am setting maximum upload size limit by providing the maxUploadSize holding value for multipartResolver edible bean. If you will look into the source lawmaking of DispatcherServlet class, you will see that a MultipartResolver variable with name multipartResolver is divers and initialized in below method.
private void initMultipartResolver(ApplicationContext context) { endeavor { this.multipartResolver = ((MultipartResolver)context.getBean("multipartResolver", MultipartResolver.class)); if (this.logger.isDebugEnabled()) { this.logger.debug("Using MultipartResolver [" + this.multipartResolver + "]"); } } grab (NoSuchBeanDefinitionException ex) { this.multipartResolver = goose egg; if (this.logger.isDebugEnabled()) this.logger.debug("Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided"); } } With this configuration, any asking with enctype as multipart/form-data will be handled by multipartResolver before passing on to the Controller class.
Leap File Upload Controller Grade
Controller class code is very unproblematic, we need to define handler methods for the uploadFile and uploadMultipleFile URIs.
FileUploadController.java code:
package com.journaldev.bound.controller; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.note.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.note.RequestParam; import org.springframework.web.bind.notation.ResponseBody; import org.springframework.web.multipart.MultipartFile; /** * Handles requests for the application file upload requests */ @Controller public class FileUploadController { private static terminal Logger logger = LoggerFactory .getLogger(FileUploadController.class); /** * Upload unmarried file using Spring Controller */ @RequestMapping(value = "/uploadFile", method = RequestMethod.Post) public @ResponseBody Cord uploadFileHandler(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { 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 + proper name); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); logger.info("Server File Location=" + serverFile.getAbsolutePath()); return "You successfully uploaded file=" + proper name; } catch (Exception e) { render "You failed to upload " + name + " => " + e.getMessage(); } } else { render "You lot failed to upload " + proper noun + " because the file was empty."; } } /** * Upload multiple file using Spring Controller */ @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.Postal service) public @ResponseBody String uploadMultipleFileHandler(@RequestParam("name") String[] names, @RequestParam("file") MultipartFile[] files) { if (files.length != names.length) return "Mandatory information missing"; Cord bulletin = ""; for (int i = 0; i < files.length; i++) { MultipartFile file = files[i]; String name = names[i]; endeavor { 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.shut(); logger.info("Server File Location=" + serverFile.getAbsolutePath()); bulletin = message + "You successfully uploaded file=" + proper noun + "<br />"; } catch (Exception e) { render "You failed to upload " + name + " => " + e.getMessage(); } } return message; } } Notice the use of Spring annotations that make our life easier and code looks more readable.
uploadFileHandler method is used to handle unmarried file upload scenario whereas uploadMultipleFileHandler method is used to handle multiple files upload scenario. Really we could take a single method to handle both the scenarios.
At present export the application as WAR file and deploy information technology into Tomcat servlet container.
When we run our application, below images shows united states the request and responses.
Spring MVC File Upload Example
You can check the server logs to know the location where the files have been stored.
Download the project from the above link and play around with it to learn more.
Source: https://www.journaldev.com/2573/spring-mvc-file-upload-example-single-multiple-files
0 Response to "Upload and View Image File Spring Mvc"
Post a Comment