SpringMVC中采用簡潔的配置實現文件上傳


1、引入依賴(Maven項目):

當然在引入依賴之前我們需要先創建一個被Maven管理的Web Project,創建方式我就不多說了。創建成功之后在SpringMVC框架的基礎之上再添加如下兩個依賴就行了:

復制代碼
 <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
 </dependency>
復制代碼

兩個依賴庫,一個用來解決文件上傳,一個簡化IO操作。

2.1、創建文件上傳頁面

這個是一個簡單的jsp頁面,我在resources文件夾中創建views文件夾,在views文件夾中創建index.jsp文件。

復制代碼
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上傳</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/user/fileupload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="上傳" />
</form>
</body>
</html>
復制代碼

這個頁面很簡單,沒啥好說的,注意action是upload就行了。

2.2創建上傳成功預覽頁面:

<body>
文件上傳,文件預覽:
<img alt="圖片" src="${file}">
</body>

 

3、SpringMVC-servlet.xml配置:

復制代碼

<!-- 文件上傳配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!--

    defaultEncoding:請求的編碼格式必須和用戶JSP的編碼一致,以便正確讀取表單中的內容。
    uploadTempDir:文件上傳過程中的臨時目錄,上傳完成后,臨時文件會自動刪除
    maxUploadSize:設置文件上傳大小上限(單位為字節)-1為無限制

  -->
  <property name="defaultEncoding" value="UTF-8" />
  <property name="maxUploadSize" value="102400000" />
  <!-- uploadTempDir可以不做設置,有默認的路徑,上傳完畢會臨時文件會自動被清理掉 -->
  <property name="uploadTempDir" value="/upload/"></property>
</bean>

復制代碼

4、編寫Controller

復制代碼

package org.sprigmvc.pag;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.sprigmvc.dao.UserDao;
import org.sprigmvc.exception.MyException;
import org.sprigmvc.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MultipartFilter;
import org.springframework.web.servlet.ModelAndView;

@SuppressWarnings("all")
@Controller
@RequestMapping("/user/")
public class UserList {

// 文件上傳
@RequestMapping("fileupload")
private String fileUpload(MultipartFile file,Model model) throws IllegalStateException, IOException {
System.out.println("fileUpload");
String filepath="G:\\FileUpload";

File files=new File(filepath);
//是否存在目錄,不存在則創建
if(files.exists()==false) {
files.mkdirs();
System.out.println("創建成功");
}

//獲取源文件名稱
String fileName=file.getOriginalFilename();
/**
* fileName.lastIndexOf(".")為獲取后綴名
* UUID.randomUUID()為獲取唯一標識,保證文件的唯一性
* */
String fileFinishName=UUID.randomUUID()+
fileName.substring(fileName.lastIndexOf("."), fileName.length());
System.out.println("fileFinishName-->"+fileFinishName);

//上傳文件到指定目錄下
files=new File(filepath+files.separator+fileFinishName);
System.out.println("fileFinishName-->"+filepath+files.separator+fileFinishName);
file.transferTo(files);

//帶回頁面預覽
model.addAttribute("file", "/files/"+fileFinishName);
return "/user/success";
}
}

復制代碼

 

5、創建Controller時返回的:"/files/"+fileFinishName ,是一個虛擬目錄,需要手動配置Tomcat的配置文件,我們這里直接用eclipse打開:

 

 

Tomcat配置信息如下(/conf/server.xml):

 

 最后的效果:

總結:

          1、引入依賴

          2、創建文件上傳頁面和預覽頁面

          3、配置SpringMNC

          4、編寫Controller

          5、設置Tomcat虛擬目錄

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM