1.jsp頁面
<form id="subtaskForm" enctype="multipart/form-data" method="post" >
<input type='file' id='file' name='file' style='width: 160px'>
<a href='javascript:void(0);' class='caissa-btn02 tool' 'uploadFile()' style='width: 80px'>上傳</a>
<a href='javascript:void(0);' class='caissa-btn02 tool' 'downFile()' style='width: 80px'>下載下傳</a>
</form>
2.js代碼
//上傳的方法
function uploadFile(){
var formData = new FormData($('#subtaskForm')[0]);
$.ajax({
type: 'POST',
url: '/platform/file/uploadFile.do',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
});
}
//下載下傳的方法
function downFile(fileName){
var url = "/platform/file/downLoadFile.do?filename="+fileName;
url = encodeURI(url);
location.href = url;
}
3.pom的maven配置
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
4.controller方法
package com.tongyi.platform.web.action;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.net.URLEncoder;
import java.util.List;
/**
* Created by admin on 2019/3/25.
*/
@Controller
@RequestMapping("/file")
public class UtilFile extends HttpServlet{
@RequestMapping("/uploadFile.do")
public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//得到上傳檔案的儲存目錄,将上傳的檔案存放于WEB-INF目錄下,不允許外界直接通路,保證上傳檔案的安全
String savePath = "D:/date/";
//上傳時生成的臨時檔案儲存目錄
String tempPath = "D:/date/tmp/";
File file = new File(tempPath);
if(!file.exists()&&!file.isDirectory()){
System.out.println("目錄或檔案不存在!");
file.mkdir();
}
//消息提示
String message = "";
try {
//使用Apache檔案上傳元件處理檔案上傳步驟:
//1、建立一個DiskFileItemFactory工廠
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//設定工廠的緩沖區的大小,當上傳的檔案大小超過緩沖區的大小時,就會生成一個臨時檔案存放到指定的臨時目錄當中。
diskFileItemFactory.setSizeThreshold(1024*100);
//設定上傳時生成的臨時檔案的儲存目錄
diskFileItemFactory.setRepository(file);
//2、建立一個檔案上傳解析器
ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
//解決上傳檔案名的中文亂碼
fileUpload.setHeaderEncoding("UTF-8");
//監聽檔案上傳進度
fileUpload.setProgressListener(new ProgressListener(){
public void update(long pBytesRead, long pContentLength, int arg2) {
System.out.println("檔案大小為:" + pContentLength + ",目前已處理:" + pBytesRead);
}
});
//3、判斷送出上來的資料是否是上傳表單的資料
if(!fileUpload.isMultipartContent(request)){
//按照傳統方式擷取資料
return;
}
//設定上傳單個檔案的大小的最大值,目前是設定為1024*1024位元組,也就是1MB
fileUpload.setFileSizeMax(1024*1024);
//設定上傳檔案總量的最大值,最大值=同時上傳的多個檔案的大小的最大值的和,目前設定為10MB
fileUpload.setSizeMax(1024*1024*10);
//4、使用ServletFileUpload解析器解析上傳資料,解析結果傳回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項
List<FileItem> list = fileUpload.parseRequest(request);
for (FileItem item : list) {
//如果fileitem中封裝的是普通輸入項的資料
if(item.isFormField()){
String name = item.getFieldName();
//解決普通輸入項的資料的中文亂碼問題
String value = item.getString("UTF-8");
String value1 = new String(name.getBytes("iso8859-1"),"UTF-8");
System.out.println(name+" "+value);
System.out.println(name+" "+value1);
}else{
//如果fileitem中封裝的是上傳檔案,得到上傳的檔案名稱,
String fileName = item.getName();
System.out.println(fileName);
if(fileName==null||fileName.trim().equals("")){
continue;
}
//注意:不同的浏覽器送出的檔案名是不一樣的,有些浏覽器送出上來的檔案名是帶有路徑的,如: c:\a\b\1.txt,而有些隻是單純的檔案名,如:1.txt
//處理擷取到的上傳檔案的檔案名的路徑部分,隻保留檔案名部分
fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1);
//得到上傳檔案的擴充名
String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1); if("zip".equals(fileExtName)||"rar".equals(fileExtName)||"tar".equals(fileExtName)||"jar".equals(fileExtName)){
request.setAttribute("message", "上傳檔案的類型不符合!!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
//如果需要限制上傳的檔案類型,那麼可以通過檔案的擴充名來判斷上傳的檔案類型是否合法
System.out.println("上傳檔案的擴充名為:"+fileExtName);
//擷取item中的上傳檔案的輸入流
InputStream is = item.getInputStream();
//得到檔案儲存的名稱
//得到檔案儲存的路徑
System.out.println("儲存路徑為:"+savePath);
//建立一個檔案輸出流
FileOutputStream fos = new FileOutputStream(savePath + fileName);
//建立一個緩沖區
byte buffer[] = new byte[1024];
//判斷輸入流中的資料是否已經讀完的辨別
int length = 0;
//循環将輸入流讀入到緩沖區當中,(len=in.read(buffer))>0就表示in裡面還有資料
while((length = is.read(buffer))>0){
//使用FileOutputStream輸出流将緩沖區的資料寫入到指定的目錄(savePath + "\\" + filename)當中
fos.write(buffer, 0, length);
}
//關閉輸入流
is.close();
//關閉輸出流
fos.close();
//删除處理檔案上傳時生成的臨時檔案
item.delete();
message = "檔案上傳成功";
}
}
} catch (FileUploadBase.FileSizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("message", "單個檔案超出最大值!!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}catch (FileUploadBase.SizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("message", "上傳檔案的總的大小超出限制的最大值!!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message = "檔案上傳失敗";
}
request.setAttribute("message",message);
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
@RequestMapping("/downLoadFile.do")
public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//得到要下載下傳的檔案名
String fileName = request.getParameter("filename");
fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
//上傳的檔案都是儲存在/WEB-INF/upload目錄下的子目錄當中
String fileSaveRootPath="D:/date/";
//處理檔案名
String realname = fileName.substring(fileName.indexOf("_")+1);
//通過檔案名找出檔案的所在目錄
//得到要下載下傳的檔案
File file = new File(fileSaveRootPath+ fileName);
//如果檔案不存在
if(!file.exists()){
request.setAttribute("message", "您要下載下傳的資源已被删除!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
//設定響應頭,控制浏覽器下載下傳該檔案
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
//讀取要下載下傳的檔案,儲存到檔案輸入流
FileInputStream in = new FileInputStream(fileSaveRootPath+ fileName);
//建立輸出流
OutputStream os = response.getOutputStream();
//設定緩存區
byte[] bytes = new byte[1024];
int len = 0;
while((len = in.read(bytes))>0){
os.write(bytes);
}
//關閉輸入流
in.close();
//關閉輸出流
os.close();
}
}
5.可能遇見的錯誤
List list = fileUpload.parseRequest(request);選擇了檔案但是得到的list值一直為0.
原因:Spring的配置檔案中已經配置了MultipartResolver,導緻檔案上傳請求已經被預處理過了,是以此處解析檔案清單為空,對應的做法是删除該段配置。