1.建立maven項目
html
在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.xmljava
咱們知道一個web項目從web.xml開始,咱們的web.xml裏面的配置以下,主要引用了下spring mvc裏面的DispatcherServletweb
代碼以下:spring
<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配置文件,內容以下:apache
<?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.代碼結果以下:api
4.前端頁碼代碼以下:spring-mvc
index.jspmvc
<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將上傳的圖片給請求過來,顯示出來,代碼以下:app
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)被系統佔用?
結果我晚上嘗試又正常了,太蹊蹺了。