1.创建maven项目
在pom.xml里面引入该依赖的jar包,pom.xm的代码如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kedacom.myupload</groupId>
<artifactId>uploaddemo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>uploaddemo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- 将jsp编译成servlet,没有的话,jsp会报错 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--spring mvc库用到的jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springVersion}</version>
</dependency>
<!-- fileUpload 解析上传的文件用到的jar-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<finalName>uploaddemo</finalName>
</build>
<properties>
<springVersion>3.2.5.RELEASE</springVersion>
</properties>
</project>
2.修改配置文件web.xml和springmvc-servlet.xml
我们知道一个web项目从web.xml开始,我们的web.xml里面的配置如下,主要引用了下spring mvc里面的DispatcherServlet
代码如下:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
我们知道DispatcherServle会自动读取springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!--扫描controller包进来,以后请求去这里面找对应的路径 -->
<context:component-scan base-package="com.kedacom.upload.controller"></context:component-scan>
<!-- 视图的解析器,/WEB-INF/jsp/+viewName+.jsp -->
<bean 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"/>
<!-- 一定要这个annotation-driven,不然获得不了静态资源,还有注意mapping的值一定不要与项目名字开头有相同的,否则会出很多问题 ,很多要通过controler的都会出问题-->
<mvc:annotation-driven/>
<!-- 映射静态资源 -->
<!--后面img引用图片路径要这个静态映射 -->
<mvc:resources location="/lupload/" mapping="/lupload/**" />
</beans>
3.代码结果如下:
4.前端页码代码如下:
index.jsp
<html>
<body>
<form action="/uploaddemo/saveuploads" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
result.jsp将上传的图片给请求过来,显示出来,代码如下:
result.jsp
<%@ page pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>上传结果</title>
</head>
<body>
<img alt="" src="${fileUrl }" />
</body>
</html>
5.控制器处理上传的文件,并保存,将要显示url传给新的页面,代码如下:
UploadController.java
package com.kedacom.upload.controller;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
//注意:这个的路径不要写成“/upload”,否则会有一个意向不到的错误。
@RequestMapping(value = "/saveuploads", method = RequestMethod.POST)
public String upload(
@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request, ModelMap model) {
System.out.println("开始");
//创建你要保存的文件的路径
String path = request.getSession().getServletContext().getRealPath("lupload");
//获取该文件的文件名
String fileName = file.getOriginalFilename();
System.out.println(path);
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
//将该文件的路径给客户端,让其可以请求该图片
model.addAttribute("fileUrl", request.getContextPath() + "/lupload/"+ fileName);
return "result";
}
}
上传成功后,我们可以在我们的硬盘上查看我们的文件的位置如下:
图片就存在lupload里面。
之前的springmvc-serlvet.xml里面的静态资源映射就是因为,这儿产生的静态资源的图片,后面要请求这个图片。
6.之前遇到的问题和解决办法;
在刚开始写这个例子的时候,遇到了一个很奇怪的问题,就是我上传文件提交的表单为post方法,但是他给我重定向为get方法,然后保存了,说没有get方法的解析函数。
我之前的index.jsp如下:
<html>
<body>
<form action="/uploaddemo/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
我的UploadController.java的代码如下:
package com.kedacom.upload.controller;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(
@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request, ModelMap model) {
System.out.println("开始");
String path = request.getSession().getServletContext().getRealPath("lupload");
String fileName = file.getOriginalFilename();
System.out.println(path);
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath() + "/lupload/"+ fileName);
return "result";
}
}
现象如下,当我点击的submit按钮,上传文件,就被其重定向为让我用get方法请求/upload方法。好像是被系统给拿去重定向,我改了一个路径/saveuploads,就好了。疑问,难道是这个路径(/upload)被系统占用?
结果我晚上尝试又正常了,太蹊跷了。