这篇文章是介绍文件上传的,由于在spring MVC上实现起来和直接在servlet中写有些不同,所以特地写了一下这篇文章,关于不同点,大家可以先阅读一下上一篇文章。好了,下面直接上代码。
jab包是jspSmartUpload.jar,如果有类似的jar包如:commons-fileupload-1.2.2,留一个即可,否则会冲突报错
首先是一个简单的页面(jsp),比较丑,但能用:
<%@ 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代码,至于为什么这样写,可以参考上一篇文章:
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中,该目录位于工程下的.metadata/.me_tcat/webapps/该工程目录/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) { } }测试时写一个按钮,点击后弹出上面那个页面就行。
文件上传后的名字是随机生成的,这块可以根据实际情况改,代码中写明白了。
还要强调的是我写的这个例子文件是上传到tomcat/webapps/项目/upload下,所以需要先在tomcat下创建一个文件夹。