這篇文章是介紹文件上傳的,由於在spring MVC上實現起來和直接在servlet中寫有些不一樣。因此特意寫了一下這篇文章,關於不一樣點,你們可以先閱讀一下上一篇文章。好了,如下直接上代碼。html
jab包是jspSmartUpload.jar,假設有相似的jar包如:commons-fileupload-1.2.2,留一個就能夠,不然會衝突報錯java
首先是一個簡單的頁面(jsp),比較醜。但能用:web
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="pragma" content="no-cache" /> <base target="_self"> <title>文件上傳</title> </head> <body> <h5>文件上傳</h5><hr/> <form id="uploadForm" action="http://localhost:8080/springMVC/fileLoad/upload.do" enctype="multipart/form-data" method="post"> <div><input type="file" size="25" maxlength="80" name="file_upload"/></div> <div><input type="submit" value="上傳"/></div> </form> </body> </html>效果圖:
而後是controller代碼,至於爲何這樣寫,可以參考上一篇文章:spring
package module.system.controller; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import module.system.common.FileLoad; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.ServletConfigAware; import org.springframework.web.context.ServletContextAware; /** * 文件上傳下載. * */ @Controller @RequestMapping("/fileLoad") public class FileLoadController implements ServletConfigAware,ServletContextAware{ private ServletContext servletContext; @Override public void setServletContext(ServletContext arg0) { this.servletContext = arg0; } private ServletConfig servletConfig; @Override public void setServletConfig(ServletConfig arg0) { this.servletConfig = arg0; } @RequestMapping(value = "/upload.do", method = RequestMethod.POST) @ResponseBody //此註解代表返回值跳過視圖處理部分。直接寫入 http response body中 public String upload(HttpServletRequest request,HttpServletResponse response) { FileLoad fileLoad = new FileLoad(); try { fileLoad.upload(request, response,servletConfig); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } }接着是FileLoad類:
package module.system.common; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jspsmart.upload.SmartFile; import com.jspsmart.upload.SmartUpload; /** * 文件上傳下載. * @author nagsh. * */ public class FileLoad{ /** * 文件上傳. * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String upload(HttpServletRequest request, HttpServletResponse response,ServletConfig config) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //新建一個SmartUpload對象 SmartUpload mySmartUpload=new SmartUpload(); String fileId = ""; try{ //上傳初始化 mySmartUpload.initialize(config, request, response); //設定每個上傳文件的最大長度 mySmartUpload.setMaxFileSize(1*512*1024); //設定總上傳數據的長度 mySmartUpload.setTotalMaxFileSize(1*1024*1024); //設定贊成上傳的文件的類型,僅僅贊成上傳java,doc,txt文件 mySmartUpload.setAllowedFilesList("java,doc,txt"); //設定禁止上傳的文件的類型,禁止上傳帶有exe,bat文件 mySmartUpload.setDeniedFilesList("exe,bat"); //上傳文件 mySmartUpload.upload(); //處理每個上傳文件 for(int i=0;i<mySmartUpload.getFiles().getCount();i++) { SmartFile file=mySmartUpload.getFiles().getFile(i); //推斷用戶是否選擇了文件 if(!file.isMissing()){ //另存到以Web應用程序的根文件夾爲文件根文件夾的文件夾下 //(聲明一下:在Myeclipse中,該文件夾位於project下的.metadata/.me_tcat/webapps/該project文件夾/upload/) //生成惟一的文件索引(日期+兩個隨機數) String fileName =file.getFileName(); String data[] = fileName.split("\\."); System.out.println(data.length); String fileType = data[1]; //文件類型 System.out.println(fileType); Date now = new Date(); DateFormat YMD = new SimpleDateFormat("yyyyMMdd");//年-月-日 String ymd = YMD.format(now);//當前年-月-日 Random random = new Random(); int r1 = random.nextInt(99999); int r2 = random.nextInt(99999); fileId = ymd+r1+""+r2; System.out.println(fileId); file.saveAs("/upload/"+fileId+"."+fileType,mySmartUpload.SAVE_VIRTUAL); } } }catch(Exception e){//異常處理 //打印本身定義異常信息 } return fileId; } public static void main(String[] args) { } }測試時寫一個button,點擊後彈出上面那個頁面便可。
文件上傳後的名字是隨機生成的,這塊可以依據實際狀況改。代碼中寫明確了。tomcat
還要強調的是我寫的這個樣例文件是上傳到tomcat/webapps/項目/upload下。因此需要先在tomcat下建立一個目錄。
app