1,導入jar包(除了導入springMVC必須包外還需Commons-io和fileupload包)
2,配置spring.xml將該配置文件放於src下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配一個control的掃描器 -->
<context:component-scan base-package="com.baojian.controller"></context:component-scan>
<bean id="FormattingConversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<!-- 自己的日期轉換器類 -->
<bean class="com.baojian.converter.DataConverter"></bean>
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="FormattingConversionServiceFactoryBean"></mvc:annotation-driven>
<!-- 配置文件上傳解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" >
<value>5242880</value>
</property>
</bean>
<!-- 配置攔截器 -->
<!-- <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.baojian.intercept.LoginIntercept"></bean>
</mvc:interceptor>
</mvc:interceptors> -->
<!-- 配置視圖解析器 -->
<!-- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
視圖前綴
<property name="prefix" value="/WEB-INF/page/"></property>
視圖後綴
<property name="suffix" value=""></property>
</bean> -->
<mvc:resources location="images/" mapping="images/**"/>
<mvc:resources location="js/" mapping="js/**"/>
</beans>
3,在web.xml中配置前端控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>springMVC01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>Encoding</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>Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>hello world</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello world</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
4,書寫控制器類
package com.baojian.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
/**
* 這是一個相當於servlet的控制器類
* @author ybj
*
*/
// 表明控制器類身份的註解
@Controller
@RequestMapping("/myController")
public class MyController00 {
// 圖片上傳方法,參數multiFile必須和前端上傳圖片時input標籤的name屬性一致
@RequestMapping("/upload")
public ModelAndView upload(HttpServletRequest request,MultipartFile multiFile) throws ServletException, IllegalStateException, IOException{
// 創建modelAndView對象
ModelAndView modelAndView = new ModelAndView();
// 得到真實路徑
String realPath = getRealPath("images",request);
// 得到新文件名
String newName = getNewName(multiFile);
File file = new File(realPath+"/"+newName);
String imageName = "images/" + newName;
modelAndView.addObject("imageName", imageName);
// 上傳文件
multiFile.transferTo(file);
System.out.println("上傳成功!");
// 跳轉頁面
modelAndView.setViewName("/index.jsp");
return modelAndView;
}
// 1,得到真實路徑
public String getRealPath(String path,HttpServletRequest request){
String realPath = request.getServletContext().getRealPath(path);
File file = new File(realPath);
// 如果該文件夾不存在,創建該文件件
if(!file.exists()){
file.mkdirs();
}
return realPath;
}
// 2,得到新文件名的方法
public String getNewName(MultipartFile file){
String uuid = UUID.randomUUID().toString();
String oldName = file.getOriginalFilename();
String suffix = oldName.substring(oldName.lastIndexOf("."),oldName.length());
String newName = uuid + suffix;
return newName;
}
}
5,書寫jsp頁面(Ajax異步請求遇到問題正在解決)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
function download(){
var conf = confirm('你確定要下載該資源嗎?');
if(conf == true){
alert("進入");
var para ={"imagePath":"${imagePath}"};
$.post("${pageContext.request.contextPath}/myController/download.action",para,
function(data){
alert("下載成功");
}
);
}else{
javascript:void(0);
}
}
</script>
</head>
<body>
請選擇要上傳的圖片:
<form action="${pageContext.request.contextPath}/myController/upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="multiFile" value="" /> <br /> <br />
<input type="submit" value="上傳" />
</form>
<img alt="" src="${pageContext.request.contextPath}/${imagePath}" height="200" weight="200">
<hr>
<font color="red">下載</font>
<a href="${pageContext.request.contextPath}/myController/download.action?imagePath=${imagePath}" > <img alt="" src="${pageContext.request.contextPath}/${imagePath}" height="200" weight="200"/></a>
<hr>
<font color="red">Ajax下載</font>
<!-- javascript:return confirm('你確定要下載該資源嗎?') -->
<img alt="" src="${pageContext.request.contextPath}/${imagePath}" height="200" weight="200" id="image" onclick="download()"/>
</body>
</html>
實現文件下載主要注意設置response.setHeader( "Content-Disposition", "attachment;filename=" + fileName); 設置圖片以附件形式打開。在控制器類中添加下載方法
// 下載標準方法的寫法
@RequestMapping(value="/download",method=RequestMethod.POST)
public ModelAndView download(HttpServletRequest request,HttpServletResponse response,String imagePath) throws ServletException, IllegalStateException, IOException{
// 創建modelAndView對象
ModelAndView modelAndView = new ModelAndView();
// 獲取服務器的真實路徑
String realPath = getRealPath(imagePath, request);
// 獲取文件名
String fileName = imagePath.substring(imagePath.indexOf("/") + 1, imagePath.length());
// 設置相應頭部信息
// response.setHeader("Content-Disposition", "attachment;fileName" + fileName);
response.setHeader( "Content-Disposition", "attachment;filename=" + fileName);
// 獲取輸出流
OutputStream output = response.getOutputStream();
// 根據真實路徑創建輸入流對象
FileInputStream input = new FileInputStream(realPath);
IOUtils.copy(input, output);
System.out.println("download success!");
return modelAndView;
}