SpringMVC single file upload, multi-File Upload, file list display, file download, springmvc File Upload

Source: Internet
Author: User

SpringMVC single file upload, multi-File Upload, file list display, file download, springmvc File Upload

Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka

This document describes in detail the single file upload, multi-File Upload, file list display, and file download of SpringMVC instances.

Download this project for free

1. Create a Web project and import related packages

Springmvc package + commons-fileupload.jar + connom-io.jar + commons-logging, jar + jstl. jar + standard. jar

The entire related package is as follows:

The project directory is as follows:

2. Configure the web. xml and SpringMVC files

(1) web. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: web = "http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0"> <! -- Front-end controller of SpringMVC --> <servlet-name> MyDispatcher </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </servlet-class> <! -- Set your own Controller xml file --> <init-param> <param-name> contextConfigLocation </param-name> <param-value>/WEB-INF/springMVC-servlet.xml </param- value> </init-param> <load-on-startup> 1 </load-on-startup> </servlet> <! -- Spring MVC configuration file ended --> <! -- Intercept settings --> <servlet-mapping> <servlet-name> MyDispatcher </servlet-name> <! -- All requests are intercepted by SpringMVC --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
(2) springMVC-servlet.xml documents

<Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://www.springframework.org/schema/context" xmlns: util = "http://www.springframework.org/schema/util" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: p = "http://www.springframework.org/schema/p" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemaLocation = "http://www.springframework.org/schema/util http: // Www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd. Org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <! -- Convert the class marked with @ Controller annotation to bean --> <context: component-scan base-package = "com. mucfc"/> <! -- Resolve the Model View name, that is, add the prefix suffix --> <bean class = "org. springframework. web. servlet. view. internalResourceViewResolver "p: prefix ="/WEB-INF/views/"p: suffix = ". jsp "/> <! -- Set the file to be uploaded. maxUploadSize =-1 indicates infinity. UploadTempDir is the temporary directory for upload --> <bean id = "multipartResolver" class = "org. springframework. web. multipart. commons. commonsMultipartResolver "p: defaultEncoding =" UTF-8 "p: maxUploadSize =" 5400000 "p: uploadTempDir =" fileUpload/temp "/> </beans>

3. Upload a single file

(1) Controller

@ Controller @ RequestMapping ("/file") public class FileController {@ RequestMapping ("/toFile") public String toFileUpload () {return "fileUpload ";} @ RequestMapping ("/toFile2") public String toFileUpload2 () {return "fileUpload2";}/*** method 1 upload a file */@ RequestMapping ("/onefile ") public String oneFileUpload (@ RequestParam ("file") CommonsMultipartFile file, HttpServletRequest request, ModelMap model) {// obtain the original file name String FileName = file. getOriginalFilename (); System. out. println ("original file name:" + fileName); // new file name String newFileName = UUID. randomUUID () + fileName; // obtain the project path ServletContext SC = request. getSession (). getServletContext (); // upload location String path = SC. getRealPath ("/img") + "/"; // set the File storage directory File f = new File (path); if (! F. exists () f. mkdirs (); if (! File. isEmpty () {try {FileOutputStream fos = new FileOutputStream (path + newFileName); InputStream in = file. getInputStream (); int B = 0; while (B = in. read ())! =-1) {fos. write (B);} fos. close (); in. close ();} catch (Exception e) {e. printStackTrace () ;}} System. out. println ("Upload image to:" + path + newFileName); // save the file address for displaying the model on the JSP page. addAttribute ("fileUrl", path + newFileName); return "fileUpload";}/*** method 2 upload a file, one at a time */@ RequestMapping ("/onefile2 ") public String oneFileUpload2 (HttpServletRequest request, HttpServletResponse response) throws Exception {CommonsMultipartRes Olver cmr = new CommonsMultipartResolver (request. getServletContext (); if (cmr. isMultipart (request) {MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request); Iterator <String> files = mRequest. getFileNames (); while (files. hasNext () {MultipartFile mFile = mRequest. getFile (files. next (); if (mFile! = Null) {String fileName = UUID. randomUUID () + mFile. getOriginalFilename (); String path = "d:/upload/" + fileName; File localFile = new File (path); mFile. transferTo (localFile); request. setAttribute ("fileUrl", path) ;}} return "fileUpload ";}}
(2) JSP: This page is used for uploading and displaying the uploaded image page fileUpload. jsp

<% @ Page language = "java" contentType = "text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%> <% @ taglib prefix =" form "uri =" http://www.springframework.org/tags/form "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> 

Run now and check the effect. Enter http: // localhost: 8080/SpringMVCLearningChapter4_1/file/toFile.


Console output result, after selecting the image

Original file name: Chrysanthemum.jpg
Upload the image to: E: \ workspace \. metadata \. plugins \ org. eclipse. wst. server. core \ tmp0 \ wtpwebapps \ SpringMVCLearningChapter4_1 \ img/templates

The image has been uploaded and can be displayed in JSP.

Let's take a look at the server path: E: \ workspace \. metadata \. plugins \ org. eclipse. wst. server. core \ tmp0 \ wtpwebapps \ SpringMVCLearningChapter4_1 \ img

Indicates that the image has been uploaded to the server.

Method 2:

Upload using file stream

/*** Method 2: upload a file at a time */@ RequestMapping ("/onefile2") public String oneFileUpload2 (HttpServletRequest request, HttpServletResponse response) throws Exception {CommonsMultipartResolver cmr = new CommonsMultipartResolver (request. getServletContext (); if (cmr. isMultipart (request) {MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request); Iterator <String> files = mRequest. getFileNames (); While (files. hasNext () {MultipartFile mFile = mRequest. getFile (files. next (); if (mFile! = Null) {String fileName = UUID. randomUUID () + mFile. getOriginalFilename (); String path = "d:/upload/" + fileName; File localFile = new File (path); mFile. transferTo (localFile); request. setAttribute ("fileUrl", path) ;}} return "fileUpload ";}

Set

<Center> <form action = "file/onefile" method = "post" enctype = "multipart/form-data"> <input type = "file" name = "file "/> <input type = "submit" value = "Upload"/> </form> In
<form action="file/onefile"
Change

<form action="file/onefile2"
Input: http: // localhost: 8080/SpringMVCLearningChapter4_1/file/toFile

Method 2: Specify the upload folder uploaded to the local edisk

PAGE result


Iv. Multifile upload

(1) Controller

@RequestMapping("/toFile2")public String toFileUpload2() {return "fileUpload2";}

/*** Upload multiple images at a time */@ RequestMapping ("/threeFile") public String threeFileUpload (@ RequestParam ("file") CommonsMultipartFile files [], HttpServletRequest request, ModelMap model) {List <String> list = new ArrayList <String> (); // obtain the project path ServletContext SC = request. getSession (). getServletContext (); // upload location String path = SC. getRealPath ("/img") + "/"; // set the File storage directory File f = new File (path); if (! F. exists () f. mkdirs (); for (int I = 0; I <files. length; I ++) {// obtain the original file name String fileName = files [I]. getOriginalFilename (); System. out. println ("original file name:" + fileName); // new file name String newFileName = UUID. randomUUID () + fileName; if (! Files [I]. isEmpty () {try {FileOutputStream fos = new FileOutputStream (path + newFileName); InputStream in = files [I]. getInputStream (); int B = 0; while (B = in. read ())! =-1) {fos. write (B);} fos. close (); in. close ();} catch (Exception e) {e. printStackTrace () ;}} System. out. println ("Upload image to:" + path + newFileName); list. add (path + newFileName);} // save the file address for displaying the model on the JSP page. addAttribute ("fileList", list); return "fileUpload2 ";}
It is actually modified in method 1 of single file upload, but it is a loop.

(2) fileUpload2.jsp display page

<% @ Page language = "java" import = "java. util. * "contentType =" text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%> <% @ taglib prefix =" form "uri =" http://www.springframework.org/tags/form "%> <% @ taglib uri =" http://java.sun.com/jsp/jstl/core "prefix =" c "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> Note that this is used
</c:forEach>
Form, jstl. jar + standard. jar

(3) Enter http: // localhost: 8080/SpringMVCLearningChapter4_1/file/toFile2 after running (note that the preceding figure is not followed by the number 2 in a single file)

Select an image and Click Upload


Console output result:


The image cannot clearly read the text:

Original file name: Desert.jpg
Upload the image to: E: \ workspace \. metadata \. plugins \ org. eclipse. wst. server. core \ tmp0 \ wtpwebapps \ SpringMVCLearningChapter4_1 \ img/templates
Original file name: Hydrangeas.jpg
Upload the image to: E: \ workspace \. metadata \. plugins \ org. eclipse. wst. server. core \ tmp0 \ wtpwebapps \ SpringMVCLearningChapter4_1 \ img/templates
Original file name: Jellyfish.jpg
Upload the image to: E: \ workspace \. metadata \. plugins \ org. eclipse. wst. server. core \ tmp0 \ wtpwebapps \ SpringMVCLearningChapter4_1 \ img/dee340d8-9cc0-41ae-9959-f7fa47ff172bJellyfish.jpg

All three images can be displayed.


Let's look at the server. This is the three files that have just been uploaded.


5. Upload file list display

(1) Controller

/*** List all images */@ RequestMapping ("/listFile") public String listFile (HttpServletRequest request, HttpServletResponse response) {// obtain the directory of the uploaded file ServletContext SC = request. getSession (). getServletContext (); // upload location String uploadFilePath = SC. getRealPath ("/img") + "/"; // set the directory for saving the file // store the Map file name to be downloaded <String, String> fileNameMap = new HashMap <String, string> (); // recursively traverse all files and directories under the filepath directory, store the File names to listfile (new File (uploadFilePath), fileNameMap) in the map set ); // File can represent a File or a directory // send the Map set to listfile. the jsp page displays the request. setAttribute ("fileNameMap", fileNameMap); return "listFile ";}
(2) JSP file listFile. jsp

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% @ taglib prefix =" c "uri =" http://java.sun.com/jsp/jstl/core "%> <! Doctype html> 

(3) Enter http: // localhost: 8080/SpringMVCLearningChapter4_1/file/listFile

These are the four images that have just been uploaded.


Vi. File Download

(1) Controller

@ RequestMapping ("/downFile") public void downFile (HttpServletRequest request, HttpServletResponse response) {System. out. println ("1"); // get the file name String fileName = request. getParameter ("filename"); System. out. println ("2"); try {fileName = new String (fileName. getBytes ("iso8859-1"), "UTF-8"); System. out. println ("3"); // obtain the directory of the uploaded file ServletContext SC = request. getSession (). getServletContext (); System. out. println ("4"); // upload location String fileSaveRootPath = SC. getRealPath ("/img"); System. out. println (fileSaveRootPath + "\" + fileName); // obtain the File to be downloaded. file = new File (fileSaveRootPath + "\" + fileName ); // if the object does not exist if (! File. exists () {request. setAttribute ("message", "The resource you want to download has been deleted !! "); System. out. println (" The resource you want to download has been deleted !! "); Return;} // processing file name String realname = fileName. substring (fileName. indexOf ("_") + 1); // sets the response header and controls the browser to download the file response. setHeader ("content-disposition", "attachment; filename =" + URLEncoder. encode (realname, "UTF-8"); // read the file to be downloaded and save it to the file input stream FileInputStream in = new FileInputStream (fileSaveRootPath + "\" + fileName ); // create output stream OutputStream out = response. getOutputStream (); // create a buffer byte buffer [] = new byte [1024]; int len = 0; // cyclically read the content in the input stream to the buffer while (len = in. read (buffer)> 0) {// output the buffer content to the browser to download the file out. write (buffer, 0, len);} // close the file input stream in. close (); // close the output stream out. close () ;}catch (Exception e ){}}

Here we download images through file streams.

Then you can select the download location.


I finally finished speaking. It took most of my time!

Download this project for free

Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.