SpringMvc下實現文件上傳

1  項目.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>//DispatcherServlet是SpringMvc的控制器。
  <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:config/hello-servlet.xml</param-value>//去這個文件路徑裏去讀取hello-servlet.xml配置文件的內容
  </init-param>
  <load-on-startup>1</load-on-startup>//表示容器在應用啓動時就加載並初始化各個Servlet

  </servlet>
  
  <servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/</url-pattern>//表示對每個服務器端的請求都會被攔截,但是一些靜態文件沒有在Controller的話則訪問請求不了,需要配置
  </servlet-mapping>
  
  <!--SpringMvc提供的編碼配置  -->
  <filter>
        <filter-name>encodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

2. hello-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xmlns:mvc="http://www.springframework.org/schema/mvc"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans  
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
      http://www.springframework.org/schema/context  
      http://www.springframework.org/schema/context/spring-context.xsd  
      http://www.springframework.org/schema/mvc  
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> 


<!-- 註解掃描包 -->
 <context:component-scan base-package="com.gaorui.Controller.Annotation"/>

 <!-- 開啓註解 -->
 <mvc:annotation-driven/>


<!-- 靜態資源訪問配置 -->
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>

//SpringMVC視圖解析器配置
<bean  id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- SpringMvc 上傳文件配置,暫時不寫限制上傳大小的參數 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <property name="defaultEncoding" value="UTF-8"/>  
        <!-- 指定所上傳文件的總大小不能超過200KB。注意maxUploadSize屬性的限制不是針對單個文件,而是所有文件的容量之和 -->  
     <!--    <property name="maxUploadSize" value="200000"/>   -->
</bean>


</beans> 


3 upload.jsp 前臺的簡單界面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>SpringMvc上傳文件問候他大爺。</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


  </head>
  
  <body>
   <h>SpringMvc上傳文件</h>
   <form action="/SpringMvc6/upload/uploadfile2"  method="post" enctype="multipart/form-data">//這裏的enctype需要改爲multipart/form-data,這是默認的上傳下載文件默認的編碼
    <input type="file" name="file" >
    <input type="submit" value="Submit">
   </form>
  </body>
</html>


4.UploadFile.java  後臺的控制器爲了方便直接進行了業務邏輯的處理,只有一個小例子就沒有分層

package com.gaorui.Controller.Annotation;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;


import javax.servlet.http.HttpServletRequest;


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.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


@Controller
@RequestMapping("/upload")
public class UploadFile {

// 先訪問該url 進入到 upload.jsp 頁面
@RequestMapping("/toUpload")
public String toUpload(){

return "upload";
}


@RequestMapping("/uploadfile")
public String upload(@RequestParam(value="file") CommonsMultipartFile file){ //@RequestParam接受前臺的數據,參數名爲“file”
String filename1=file.getOriginalFilename(); //得到文件名
System.out.println(file.getOriginalFilename());
if(!filename1.isEmpty()){//作基本不爲空的判斷,保證代碼的安全性
try {
// FileInputStream in = new FileInputStream("D:/"+new Date().getTime()+filename);
String filename2 = "D:/"+filename1;//設置文件保存路徑
FileOutputStream os = new FileOutputStream(filename2); //設置文件輸出流

InputStream in = file.getInputStream();//設置文件輸入流in得到前臺傳遞過來的流

//下面就是java最基本的數據寫入文件了
int a =0;
byte[] b = new byte[1024];
while((a=in.read(b))!=-1){
os.write(b,0,a);
}
os.flush();
os.close();
in.close();

} catch (Exception e) {
e.printStackTrace();
}
}
return "uploadsuccess";
}

/*@RequestMapping("/uploadfile2")
public String uploadfile2(HttpServletRequest request){
CommonsMultipartResolver cmr =new CommonsMultipartResolver(request.getSession().getServletContext());
if(cmr.isMultipart(request)){
MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest) request;
Iterator<String> iter = mhsr.getFileNames();
while(iter.hasNext()){
MultipartFile file = mhsr.getFile((String)iter.next());
String filename = file.getOriginalFilename();
String path ="E:/"+filename;
File file2 = new File(path);
try {
file.transferTo(file2);
} catch (IllegalStateException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}
}

return "uploadsuccess";
}*/


}

項目路徑,只需要看xml文件的位置和jsp文件的位置即可,其他包裏的內容可以忽略


下一篇將是SpringMvc上傳文件的優化。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章