一、spring配置文件
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 开启注解包扫描 -->
<context:component-scan
base-package="cn.hidm.springmvc"></context:component-scan>
<!-- 使用默认的Servlet响应静态文件 -->
<mvc:default-servlet-handler />
<!-- 开启注解驱动 -->
<mvc:annotation-driven />
<!-- 配置视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- spring文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="DefaultEncoding" value="UTF-8" />
<!-- 最大上传文件大小 字节(byte)为单位 -->
<property name="MaxUploadSize" value="1048576" />
<property name="MaxInMemorySize" value="4096" />
</bean>
</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">
<!-- spring前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springApplication.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置spring编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 文件上传必须配置 -->
<multipart-config></multipart-config>
</web-app>
三、controller类
package cn.hidm.springmvc.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.java2d.pipe.BufferedPaints;
@Controller
@RequestMapping(value = "/uploadAndDownload")
public class FileController {
@RequestMapping(value = "/upload")
public String upload(HttpServletRequest request, HttpServletResponse response)
throws IllegalStateException, IOException {
// 获取服务器保存路径
String path = request.getSession().getServletContext().getRealPath("") + "\\upload\\";
System.out.println(path);
// 获取spring文件解析器
CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// 判断请求参数是否是文件
System.out.println(resolver.isMultipart(request));
if (resolver.isMultipart(request)) {
// 将request转换为MultipartRequest
MultipartRequest multipartRequest = (MultipartRequest) request;
// 获取所有文件名称
Iterator<String> names = multipartRequest.getFileNames();
while (names.hasNext()) {
// 根据文件名获取文件
MultipartFile file = multipartRequest.getFile(names.next().toString());
// 为防止文件名重复,重新拼接文件名
String filename = UUID.randomUUID().toString().replace("-", "") +"-"+ file.getOriginalFilename();
// 创建存储文件路径
String filePath = path + filename;
// 在存储路径创建文件
File newFile = new File(filePath);
// 创建父目录
if (newFile.getParentFile() != null && !newFile.getParentFile().isDirectory()) {
newFile.getParentFile().mkdirs();
}
// 将请求中的文件写入到服务器
file.transferTo(newFile);
}
}
return "success";
}
@RequestMapping(value="filelist")
public String getfilelist(HttpServletRequest request, HttpServletResponse response) {
//记录每个文件的位置和名称
Map<String, String> map = new HashMap<String, String>();
//获取下载路径
String path = request.getSession().getServletContext().getRealPath("") + "\\upload\\";
//获取项目根目录
String projectPath = request.getServletContext().getContextPath();
System.out.println("projectPath " + projectPath);
//获取下载路径下所有文件的名称及文件的路径
File files = new File(path);
if (files.isDirectory()) {
File[] listFiles = files.listFiles();
for (int i=0; i<listFiles.length; i++) {
System.out.println(listFiles[i].getPath());
//key 访问文件的uri /projectName/xxx?filename value 上传文件名
// map.put(listFiles[i].getPath(), listFiles[i].getName().substring(33));
map.put(projectPath+"/uploadAndDownload/download?filename="+listFiles[i].getName(), listFiles[i].getName().substring(33));
}
}
request.setAttribute("map", map);
return "filelist";
}
/**
* 传统方式实现文件下载 方式一:
* @param filename
* @param request
* @param response
* @return
*/
/*
* @RequestMapping(value="/download") public String download(@RequestParam
* String filename, HttpServletRequest request, HttpServletResponse response) {
* //设置响应体和响应编码 response.setContentType("text/html;charset=utf-8"); try {
* //确认请求编码为utf-8 request.setCharacterEncoding("UTF-8"); } catch
* (UnsupportedEncodingException e) { e.printStackTrace(); } BufferedInputStream
* bis = null; BufferedOutputStream bos = null;
*
* try { //文件下载路径 String downloadPath =
* request.getSession().getServletContext().getRealPath("/upload/") + filename;
* System.out.println("downloadPath为: " + downloadPath); //获取下载文件大小 long
* fileLength = new File(downloadPath).length(); //设置以二进制传输
* response.setContentType("application/x-msdownload"); //设置下载提示框
* response.setHeader("Content-disposition", "attachment;filename="+new
* String(filename.getBytes("utf-8"),"iso-8859-1")); //设置文件大小
* response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new
* BufferedInputStream(new FileInputStream(downloadPath)); bos = new
* BufferedOutputStream(response.getOutputStream()); byte[] buff = new
* byte[2048]; int read; while((read = bis.read(buff, 0, buff.length)) != -1) {
* bos.write(buff, 0, read); } } catch (UnsupportedEncodingException e) {
* e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace();
* } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null)
* try { bis.close(); } catch (IOException e) { e.printStackTrace(); } if (bos
* != null) try { bos.close(); } catch (IOException e) { e.printStackTrace(); }
* }
*
* return null;
*
* }
*/
/**
* ResponseEntity 方式二
* @param filename
* @param request
* @param response
* @return
*/
@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(@RequestParam String filename, HttpServletRequest request, HttpServletResponse response) {
//解决文件名中文乱码
String fileName;
//读取文件
byte[] buff;
try {
//设置请求编码格式
request.setCharacterEncoding("UTF-8");
fileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
buff = null;
InputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/upload/")+ fileName);
buff = new byte[is.available()];
is.read(buff);
HttpHeaders headers = new HttpHeaders();
//通知浏览器以attachment(下载方式)打开图片
headers.add("Content-Disposition", "attchement;filename=" + fileName);
//application/octet-stream二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//文件下载的Http协议中的状态最好使用HttpStatus.OK。
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(buff, headers, statusCode);
return entity;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
四、页面(filelist.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件列表</title>
</head>
<body>
<div>
<table>
<c:forEach items="${map }" var="m" >
<a href="${m.key }">${m.value }</a><br/>
</c:forEach>
</table>
</div>
</body>
</html>
五、页面(hello.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>springmvc</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function submitData() {
//$('#formData').submit(); //Jquery提交方式
document.getElementById("formData").submit(); //js提交方式
}
//jquery事件
function ajaxData() {
$("#ajaxData").click(function() {
var formname;
var formage;
formname = $("nameId").val();
formage = $("ageId").val();
alert(formage)
$("#formData").ajax({
type: "get",
dataType: "html",
url: "/springmvc-xml/hello/ajaxForm",
data: {
name: formname,
age: formage
},
success: function(msg) {
if (msg != "") {
console.log(msg);
} else {
console.log("无异常");
}
}
});
});
}
//jquery ajax请求 函数调用
function formData() {
var formname;
var formage;
formname = $("#nameId").val();
formage = $("#ageId").val();
alert(formage);
$.ajax({
async: false,
type: "post",
dataType: "html",
url: "/springmvc-xml/hello/ajaxForm",
data: {
name: formname,
age: formage
},
success: function(msg) {
if (msg != "") {
console.log(msg);
} else {
console.log("无异常");
}
}
});
$("#uploadId").click(upload); //给uploadId绑定click事件
function upload () {
var formname = document.getDocumentById("formId");
var formData = new FormData(formname);
$.ajax({
url: "/springmvc-xml/hello/upload",
type: "post",
data: formData,
contentType: false,
porcessData: false,
success: function(returnData) {
alert(returnData);
}
});
}
}
</script>
</head>
<body>
<!-- 1. submit提交方式 -->
<h2>表单提交方式一: submit提交方式</h2>
<form action="/springmvc-xml/hello/objectMapping" method="post">
<input type="text" name="name" value="张三"> <input type="text"
name="age" value="18"> <input type="submit" name="submit"
value="提交">
</form>
<h2>表单提交方式二: iframe页面无刷新提交方式</h2>
<form action="/springmvc-xml/hello/iframe" method="post"
target="iframe">
<input type="text" name="name" value="李四"> <input type="text"
name="age" value="19"> <input type="submit" name="submit"
value="提交">
</form>
<iframe name="iframe" style="display: none"></iframe>
<!-- <iframe name="iframe" hidden="hidden"></iframe> -->
<!-- js Jquery提交表单 -->
<h2>表单提交方式三: js、Jquery提交方式</h2>
<form action="/springmvc-xml/hello/jsAndJquery" method="post"
id="formData">
<input type="text" name="name" value="王五"> <input type="text"
name="age" value="20">
<!-- <input type="submit" name="submit" value="提交"> -->
<button function="submitData()">提交</button>
</form>
<!-- ajax提交表单 -->
<h2>表单提交方式四: ajax提交表单</h2>
<form id="formData">
<input id="nameId" type="text" name="name" value="赵六">
<input id="ageId" type="text" name="age" value="21">
<!-- <input type="submit" name="submit" value="提交"> -->
<button id="ajaxData" οnclick="formData()">提交</button>
</form>
<h2>上传文件 ajax 提交</h2>
<!-- 文件上传 -->
<!-- multiple是H5中的属性,可实现多文件上传 -->
<form id="formId" enctype="multipart/form-data">
<input id="nameId" type="file" name="filename" multiple="multiple">
<input id="uploadId" type="button" value="上传" >
</form>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
pageContext.setAttribute("basePath",basePath);
%>
<!-- 文件上传 表单提交 -->
<form action="/springmvc-xml/uploadAndDownload/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple="multiple">
<input type="submit" value="上传" >
</form>
<!-- 文件上传 表单提交 -->
<form action="${pageScope.basePath }/uploadAndDownload/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple="multiple">
<input type="submit" value="上传" >
</form>
<!-- 文件下载 -->
<h2><a href="${pageScope.basePath }/uploadAndDownload/filelist">下载文件页面</a></h2>
</body>
</html>
六、上传成功页面(success.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>springmvc</title>
</head>
<body>
上传成功
</body>
</html>