springmvc文件上传下载
注意:
1 get和post请求时,获取参数的方法是不一样的。
2 下载文件时,可能文件名中包含%28或者%29,出现这种情况是是urlEncoder的encode方法将小括号编码了,而在游览器端没有解码%28,所以下载的文件名出现了%28的符号。
这里是将%28替换为“(”,将%29 替换为“)”,即对小括号不进行编码
上传文件的方法
@Controller @RequestMapping("/file") public class FileController { @PostMapping("/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) { if (!file.isEmpty()) { Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss_"); String prefix = dateFormat.format(date); String saveFileName = prefix + file.getOriginalFilename(); File saveFile = new File(request.getSession().getServletContext().getRealPath("/upload/") +"/" +saveFileName); if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile)); out.write(file.getBytes()); out.flush(); out.close(); return "success"; } catch (FileNotFoundException e) { e.printStackTrace(); return "failure"; } catch (IOException e) { e.printStackTrace(); return "failure"; } } else { return "failure"; } } }
下载文件和删除文件的方法
@Controller @RequestMapping public class DownloadFileController { @Autowired private ServletContext servletContext; @RequestMapping(value = "/testDownload", method = RequestMethod.GET) public void Download(HttpServletRequest req , HttpServletResponse res) throws Exception { String fileName = new String(req.getParameter("name").getBytes("ISO-8859-1"),"utf-8"); String type = new String(req.getParameter("type").getBytes("ISO-8859-1"),"utf-8"); res.setHeader("content-type", "application/octet-stream"); res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8").replaceAll("%28", "(").replaceAll("%29", ")")); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = res.getOutputStream(); bis = new BufferedInputStream(new FileInputStream( new File(servletContext.getRealPath("/upload/") +"/"+type+"/"+fileName))); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("success"); } @RequestMapping(value = "/delfile", method = RequestMethod.GET) public void delfile(HttpServletRequest req , HttpServletResponse res) throws Exception { String fileName = new String(req.getParameter("name").getBytes("ISO-8859-1"),"utf-8"); String type = new String(req.getParameter("type").getBytes("ISO-8859-1"),"utf-8"); File file = new File(servletContext.getRealPath("/upload/") +"/"+type+"/"+fileName); if (file.exists() && file.isFile()) { if (file.delete()) { System.out.println("删除单个文件" + fileName + "成功!"); return ; } } } }
文件列表显示方法
@Controller @RequestMapping public class ToFileListController { @Autowired private ServletContext servletContext; @RequestMapping("/fileList/{type}") public String fileList(Model model, @PathVariable("type") String type) { ArrayList<String> list = new ArrayList<String>(); ArrayList<String> files = getFiles(servletContext.getRealPath("/upload/" + type)); for (int i = 0; i < files.size(); i++) { File tempFile = new File(files.get(i).trim()); String fileName = tempFile.getName(); list.add(fileName); } Collections.sort(list, new Comparator<String>() { @Override public int compare(String o1, String o2) { String newO1 = o1.substring(0, 14); String newO2 = o2.substring(0, 14); return -newO1.compareTo(newO2); } }); model.addAttribute("files", list); if ("android".equals(type)) { return "fileList"; }return ""; } public static ArrayList<String> getFiles(String path) { ArrayList<String> files = new ArrayList<String>(); File file = new File(path); File[] tempList = file.listFiles(); for (int i = 0; i < tempList.length; i++) { if (tempList[i].isFile()) { files.add(tempList[i].toString()); } } return files; } }
前台html
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>文件列表</title> <style type="text/css"> a{ text-decoration:none; } table , td ,th{ border:1px solid black; border-collapse:collapse;/*细线表格,合并边框*/ } </style> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.js"></script> </head> <body> <div style="margin-top: 20px"></div> <table id="content" width="800" border="0" cellspacing="0" cellpadding="0"> <c:forEach items="${files}" var="user" varStatus="status"> <tr align="center"> <td height="40px"> ${status.index}</td> <td> ${user}</td> <td><a href="/testDownload?type=android&name=${user}">下载</a></td> <td><a href="javascript:void(0)" onclick='delfile("${user}");'>删除</a></td> </tr> </c:forEach> </table> <!-- js部分 --> <script> function delfile(name){ //alert(name); $.get("/delfile", {name:name,type:"android"},function(){ window.location.reload(); }); } </script> </body> </html>
设置springmvc的配置文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <property name="maxUploadSize" value="5242440"></property> </bean>