ssm文件上传下载比较详细的案例
背景:ssm框架
接下来,我会介绍单文件上传,下载,多文件的上传,下载,使用ajax进行文件的上传下载,和普通的表单提交的文件上传下载。
只要做项目,总是少不了文件的操作,好了废话不多说,直接上代码!
前提:需要在springmvc的配置文件里面加一个文件解析器,这个必须要有!!!
1 <!-- 定义文件解释器 --> 2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 3 <!-- 设置默认编码 --> 4 <property name="defaultEncoding" value="utf-8"></property> 5 <!-- 上传图片最大大小5M--> 6 <property name="maxUploadSize" value="5242440"></property> 7 </bean>
随便提下:需要的jar包,我项目使用的maven构建,直接添加的依赖,jar包是下面两个:
commons-fileupload-1.3.2.jar
commons-io-2.2.jar
一、单文件的文件上传、下载
上传:前台
<form id ="form2" action="load/upload2" enctype="multipart/form-data" method="post"> <input type = "file" name= 'file' /> <input type="text" name="name" value="dzf"/> <input type="button" id = "button2" value="ajax上传" onclick="fileupload2()"> <input type ="submit" value="直接上传"> </form>
1 function fileupload2(){ 2 var formData = new FormData($("#form2")[0]); 3 $.ajax({ 4 url:'load/upload2', 5 type:'post', 6 data:formData, 7 //必须false才会自动加上正确的Content-Type 8 contentType: false, 9 //必须false才会避开jQuery对 formdata 的默认处理 10 //XMLHttpRequest会对 formdata 进行正确的处理 11 processData: false, 12 success:function(data){ 13 alert(data); 14 }, 15 error:function(data){ 16 alert(data); 17 alert("后台发生异常"); 18 }, 19 cache:false, 20 async:true 21 }); 22 }
后台:
1 /** 2 * 单个文件上传 3 * @param request 4 * @return 5 */ 6 @RequestMapping(value="/upload2",produces="text/html;charset=utf-8") 7 @ResponseBody 8 private String upload2(@RequestParam("file")CommonsMultipartFile partFile,HttpServletRequest request) { 9 try { 10 String path = request.getServletContext().getRealPath("/upload"); 11 String name = request.getParameter("name"); 12 log.info("其他的参数{}",name); 13 log.info("upload2---------------start---------------------"); 14 log.info("这个临时文件的路径是[{}]", path); 15 String filename = partFile.getOriginalFilename(); 16 log.info("文件的名字:{}",filename); 17 File file = new File(path+"/"+filename); 18 InputStream inputStream = partFile.getInputStream(); 19 FileUtils.copyInputStreamToFile(inputStream, file); 20 if(inputStream!=null){ 21 inputStream.close(); 22 } 23 return "文件上传成功!"; 24 } catch (Exception e) { 25 e.printStackTrace(); 26 return "文件上传失败!"; 27 } 28 }
下载:前台
1 <form action="load/down1" name="form3" id = "form3" method="post"> 2 <input type = "submit" value="普通文件下载"> 3 </form>
后台:
1 /** 2 * 文件下载 3 * 单个文件下载 4 * @param request 5 * @return 6 * @throws IOException 7 */ 8 @RequestMapping("/down1") 9 private void down(HttpServletRequest request,HttpServletResponse response) throws IOException { 10 String path = request.getServletContext().getRealPath("/upload"); 11 File file = new File(path); 12 File[] files = file.listFiles(); 13 String name = files[0].getName();//随机获取一个文件,实际中按需编写代码 14 System.out.println("文件的名字:"+name); 15 response.addHeader("content-disposition", "attachment;filename="+name); 16 FileUtils.copyFile(files[0], response.getOutputStream()); 17 }
二、多文件的上传和下载
上传-前台:
1 <form id ="form5" action="load/upload3" enctype="multipart/form-data" method="post"> 2 <input type = "file" name= 'file' /> 3 <input type = "file" name= 'file' /> 4 <input type = "file" name= 'file' /> 5 <input type="text" name="name" value="dzf"/> 6 <input type="button" id = "button2" value="多文件ajax上传" onclick="fileupload3()"> 7 <input type ="submit" value="多文件直接上传"> 8 </form>
1 function fileupload3(){ 2 var formData = new FormData($("#form5")[0]); 3 $.ajax({ 4 url:'load/upload3', 5 type:'post', 6 data:formData, 7 //必须false才会自动加上正确的Content-Type 8 contentType: false, 9 //必须false才会避开jQuery对 formdata 的默认处理 10 //XMLHttpRequest会对 formdata 进行正确的处理 11 processData: false, 12 success:function(data){ 13 alert(data); 14 }, 15 error:function(data){ 16 alert(data); 17 alert("后台发生异常"); 18 }, 19 cache:false, 20 async:true 21 }); 22 }
上传-后台:
1 /** 2 * 多个文件上载 3 * @param request 4 * @return 5 */ 6 @RequestMapping(value="/upload3",produces="text/html;charset=utf-8") 7 @ResponseBody 8 private String upload3(@RequestParam("file")CommonsMultipartFile[] partFiles,HttpServletRequest request) { 9 InputStream inputStream = null; 10 try { 11 String path = request.getServletContext().getRealPath("/upload"); 12 String name = request.getParameter("name"); 13 log.info("其他的参数{}",name); 14 log.info("upload2---------------start---------------------"); 15 log.info("这个临时文件的路径是[{}]", path); 16 for (int i = 0; i < partFiles.length; i++) { 17 String filename = partFiles[i].getOriginalFilename(); 18 log.info("文件的名字:{}",filename); 19 File file = new File(path+"/"+filename); 20 inputStream = partFiles[i].getInputStream(); 21 FileUtils.copyInputStreamToFile(inputStream, file); 22 } 23 if(inputStream!=null){ 24 inputStream.close(); 25 } 26 return "文件上传成功!"; 27 } catch (Exception e) { 28 e.printStackTrace(); 29 return "文件上传失败!"; 30 } 31 }
一次性下载多个文件,我们需要把文件放到一个压缩包里去
下载-前台:
1 <form action="load/down2" name="form4" id = "form4" method="post"> 2 <input type = "submit" value="压缩文件下载"> 3 </form>
下载-后台:
1 /** 2 * 文件下载,一下次下载多个文件 3 * 思路:先将多个文件压缩到一个压缩包里去,然后传到前台 4 * @param request 5 * @return 6 * @throws IOException 7 */ 8 @RequestMapping("/down2") 9 private void down2(HttpServletRequest request,HttpServletResponse response) throws IOException { 10 String path = request.getServletContext().getRealPath("/upload"); 11 File file = new File(path); 12 File[] files = file.listFiles(); 13 File zipFile =new File("test.zip"); 14 if(!zipFile.exists()){ 15 zipFile.createNewFile(); 16 } 17 String zipName = zipFile.getName(); 18 log.info("压缩文件的名字:{}",zipName); 19 response.addHeader("Content-Disposition", "attachment;filename="+zipName); 20 //定义输出类型 21 // response.setContentType("application/zip"); 22 ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); 23 BufferedInputStream in =null; 24 log.info("文件的个数{}",files.length); 25 for(int i = 0;i<files.length;i++){ 26 String name = files[i].getName(); 27 System.out.println("文件的名字:"+name); 28 ZipEntry zipEntry = new ZipEntry(name); 29 zip.putNextEntry(zipEntry); 30 in = new BufferedInputStream(new FileInputStream(files[i])); 31 int len = 0; 32 byte [] btyes = new byte[1024*4]; 33 while((len=in.read(btyes))!=-1){ 34 zip.write(btyes, 0, len); 35 } 36 } 37 zip.flush(); 38 zip.close(); 39 in.close(); 40 FileUtils.copyFile(zipFile, response.getOutputStream()); 41 if(zipFile.exists()){ 42 if(zipFile.delete()){ 43 log.info("压缩包删成功!!"); 44 }else{ 45 log.info("压缩包产出失败!!"); 46 } 47 48 } 49 }
到此,文件的上传、下载实例代码已经全部结束!
越努力越幸运