SpringMVC的文件上传:
SpringMVC为文件上传提供了直接的支持,这种支持是通过即插即用的MultipartResolver实现的。
1.导入依赖
添加文件上传相关依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
2.springMVC-servlet的配置:
<?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" xmlns:aop="http://www.springframework.org/schema/aop"
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.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- 通过context:component-scan元素扫描指定包下的控制器-->
<!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
<context:component-scan base-package="com.zking.ssm"/>
<!--开启MVC注解-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--3) ViewResolver 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置文件上传解析器(CommonsMultipartResolver)-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 文件最大大小(字节) 1024*1024*50=50M-->
<property name="maxUploadSize" value="52428800"></property>
<!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
<!--4) 单独处理图片、样式、js等资源 -->
<!--<mvc:resources location="/css/" mapping="/css/**"/>-->
<mvc:resources location="/images/" mapping="/images/**"/>
<!--<mvc:resources location="/js/" mapping="/js/**"/>-->
</beans>
3.web.xml配置
<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">
<display-name>Archetype Created Web Application</display-name>
<!-- Spring和web项目集成start -->
<!-- spring上下文配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 读取Spring上下文的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring和web项目集成end -->
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 中文乱码处理 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--web.xml 3.0的新特性,是否支持异步-->
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
<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>
<!--web.xml 3.0的新特性,是否支持异步-->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4.BookMapper.xml上传方法:
<update id="uploadPath" parameterType="com.zking.ssm.model.Book"> update t_mvc_book set filename = #{filename,jdbcType=VARCHAR} where bid = #{bid,jdbcType=VARCHAR} </update>
5.controller配置:
package com.spring.ssm.controller;
import com.spring.ssm.model.Book;
import com.spring.ssm.service.BookService;
import com.spring.ssm.util.PageBean;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
/**
* @author cst
* @site www.xiaomage.com
* @company xxx公司
* @create 2018-12-21 17:04
*/
@Controller
@RequestMapping("/book")
public class BookController {
private String servicePath="/imgs/";
private String localPath="C:/Users/2018121005/Pictures/Camera Roll/";
@Autowired
private BookService bookService;
//上传方法
@RequestMapping("/toUpload/{bid}")
public String uploadPath(HttpServletRequest request,@PathVariable(value = "bid") String bid){
Book book1 = bookService.selectByPrimaryKey(bid);
request.setAttribute("book",book1);
return "upload";
}
@RequestMapping("/upload/{bid}")
public String uploadPath(MultipartFile file, HttpServletRequest request, Book book,@PathVariable(value = "bid") String bid){
//得到上传的文件名
String fileName=file.getOriginalFilename();
String realPath=request.getServletContext().getRealPath(servicePath+fileName);
System.out.println(realPath);
try {
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(realPath));
book.setFilename(fileName);
int i = this.bookService.uploadPath(book);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/book/list";
}
//下载方法
@RequestMapping("/downLoad")
public String downLoad(String file, HttpServletResponse response, HttpServletRequest request){
response.setContentType("image/jpg");
response.setHeader("Content-Disposition","attachment;filename="+file);
try {
String realPath=request.getServletContext().getRealPath(servicePath+file);
FileUtils.copyFile(new File(realPath),response.getOutputStream());
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
6.JSP页面:
bookList.jsp 展示页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/zking" prefix="z" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="from" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function add(){
window.location.href="${pageContext.request.contextPath}/book/toAdd";
}
function update(bid){
window.location.href = "${pageContext.request.contextPath}/book/toUpdate/"+bid;
}
function del(bid){
window.location.href = "${pageContext.request.contextPath}/book/delete/"+bid;
}
function uploadPath(bid) {
window.location.href = "${pageContext.request.contextPath}/book/toUpload/"+bid;
}
function downLoad(filename) {
window.location.href = "${pageContext.request.contextPath}/book/downLoad/"+filename;
}
</script>
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/book/list"
method="post">
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<button onclick="add();">新增</button>
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>图片</td>
<td>操作</td>
</tr>
<c:forEach items="${bookList }" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
<td><img src="${pageContext.request.contextPath}/book/opAs?file=${b.filename}" style="width: 30px;height: 30px" ></td>
<td>
<button onclick="update(${b.bid });">修改</button>
<button onclick="del(${b.bid });">删除</button>
<button onclick="uploadPath(${b.bid });">上传</button>
<a href="${pageContext.request.contextPath}/book/downLoad?file=${b.filename}">下载</a>
</td>
</tr>
</c:forEach>
</table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
upload.jsp 下载页面
<%--
Created by IntelliJ IDEA.
User: 2018121005
Date: 2018/12/25
Time: 19:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script type="text/javascript">
function doSubmit(bid){
var bookForm = document.getElementById("bookForm");
if(bid){
bookForm.action = '${pageContext.request.contextPath}/book/upload/'+bid;
}
bookForm.submit();
}
</script>
</head>
<body>
<form id="bookForm" method="post" action="" enctype="multipart/form-data">
<input type="file" name="file"> <!--name="file" 要跟后台方法参数 MultipartFile file 一致-->
<input type="submit" value="ok" onclick="doSubmit('${book.bid}');">
</form>
</body>
</html>
页面信息