SpringMVC realize the file upload support by MultipartResolver (multi-component parser) object.
MultipartResolver is an interface object, we need to complete the work of uploading files through its implementation class CommonsMultipartResolver.
1. Using MultipartResolver objects Bean configuration in 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:annotation-config/> <context:component-scan base-package="com.wxy.controller"/> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> <property name="maxUploadSize" value="2097152" /> </bean> </beans>
2.fileUpload.jsp upload page
<% @ Page contentType = "text / HTML; charset = UTF-. 8" Language = "Java"%> <HTML> <head> <title> File Upload </ title> <Script> <% - fill determines whether upload who has selected and uploaded -%> function Check () { var name = document.getElementById ( "name") value ();. var name = document.getElementById ( "file") value ();.
IF (name == "") { Alert ( "please fill out the upload man"); return false; } IF (file.length == 0 || file == "") { Alert ( "Please select a file to upload"); return false; } return true; } </script> </ head> <body> <% - the enctype = "multipart / form-Data" in binary form data stream processing -%> <form Action = "$ {} /fileUpload.action pageContext.request.contextPath" Method = "post" enctype = "multipart / form-data" onsubmit = "return check ()"> Upload al: <input id = "name" type = "text" name = "name" /> <br/> select file : <INPUT ID = "file" type = "file" name = "UploadFile" multiple = "multiple" /> a <% - multiple select multiple files to upload properties -%> <INPUT type = "Submit "value =" file upload "/> </ form> </ body> </ HTML>
3.fileDownload.jsp download page
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %> <%@ page import="java.net.URLEncoder" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>文件下载</title> </head> <body> <a href="${pageContext.request.contextPath}/download.action?filename=<%=URLEncoder.encode("图像.txt","UTF-8")%>">文件下载</a> </body> </html>
4.FileUploadAndDownloadController.java file upload and download controller class
复制代码 使用SMM框架开发企业级应用----- package com.wxy.controller; mport org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.net.URLEncoder; import java.util.List; import java.util.UUID; @Controller("controller") public class FileUploadAndDownloadController { @RequestMapping("/tofileUpload") public String toupload(){ return "fileUpload"; } @RequestMapping("/tofiledownload") public String todownload(){ return "download"; } @RequestMapping("/fileUpload.action") public String handleFormUpload(@RequestParam("name") String name, @RequestParam("uploadfile") List<MultipartFile> uploadfile, HttpServletRequest request) { if (!uploadfile.isEmpty() && uploadfile.size() > 0) { for (MultipartFile file : uploadfile) { String originalFilename = file.getOriginalFilename(); String dirPath = request.getServletContext().getRealPath("/upload/"); File filePath = new File(dirPath); if (!filePath.exists()) { filePath.mkdirs(); } String newFilename = name +"_" + originalFilename; try { file.transferTo(new File(dirPath + "_"+newFilename)); } catch (Exception e) { e.printStackTrace(); return "error"; } } return "success"; } else { return "error"; } } @RequestMapping("/download.action") public ResponseEntity<byte[]> filedownload(HttpServletRequest request,String filename) throws Exception{ String path = request.getServletContext().getRealPath("/upload"); File file = new File(path+File.separator+filename); filename = this.getFilename(request,filename); HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment",filename); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK); } public String getFilename(HttpServletRequest request,String filename) throws Exception{ String[] IEBrowserKeyWord = {"MSIE","Trident","Edge"}; String userAgent = request.getHeader("User-Agent"); for(String keyWord:IEBrowserKeyWord){ if(userAgent.contains(keyWord)){ return URLEncoder.encode(filename,"UTF-8"); } } return new String(filename.getBytes("UTF-8"),"ISO-8859-1"); } }