一、简介
使用form表单进行需要为form添加enctype="multipart/form-data" 属性,除此之外还需要将表单的提交方法改成post,如下 method="post"。
二、示例
1、表单文件上传
网页代码如下:
1 2 3 4 5 624 25
后端上传处理代码:
1 /** 2 *使用springmvc处理文件上传 3 */ 4 @RequestMapping("upload") 5 @ResponseBody 6 public boolean upload(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws UnsupportedEncodingException { 7 String path = request.getSession().getServletContext().getRealPath(""); 8 Calendar calendar = Calendar.getInstance(); 9 calendar.setTime(new Date());10 request.setCharacterEncoding("UTF-8");11 path = String.format("%s\\%s\\%s\\%s\\%s\\%s", path, "upload", "file", calendar.get(calendar.YEAR),12 calendar.get(calendar.MONTH), calendar.get(calendar.DAY_OF_MONTH));13 File filepath = new File(path);14 if (!filepath.exists()) {15 filepath.mkdirs();16 }17 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;18 获得文件19 MultipartFile multipartFile = multipartRequest.getFile("xlsfile");20 OutputStream os = null;21 InputStream is = null;22 File uploadFile = null;23 try {24 is = multipartFile.getInputStream();25 uploadFile = new File(filepath, System.currentTimeMillis() + ".xls");26 os = new FileOutputStream(uploadFile);27 IOUtils.copy(is, os);//使用commons-io组件进行文件流的处理28 os.flush(); 29 } catch (IOException e) {30 e.printStackTrace();31 return false;32 }finally{33 IOUtils.closeQuietly(os);34 IOUtils.closeQuietly(is);35 }36 return true;37 }
2、文件下载
1 /** 2 *使用springmvc进行文件下载处理 3 */ 4 @RequestMapping({ "/template" }) 5 public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) 6 throws UnsupportedEncodingException { 7 String path = request.getSession().getServletContext().getRealPath(""); 8 String filename = "模板文件.xls"; 9 File file = new File(path + "\\file\\templagte\\" + filename);10 String userAgent = request.getHeader("User-Agent");11 byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题12 String fileName = new String(bytes, "ISO-8859-1"); 13 // 设置输出的格式14 response.setContentType("multipart/form-data");15 response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));16 17 InputStream inStream = null;18 try {19 inStream = new FileInputStream(file);20 IOUtils.copy(inStream, response.getOutputStream());//使用commons-io组件进行文件流的处理21 } catch (IOException e) {22 e.printStackTrace();23 }finally{24 IOUtils.closeQuietly(inStream);25 }