标签:
文件上传
文件上传需要用到两个类,MultipartFile和MultipartHttpServletRequest,它们都是在spring的web包中,同时需要在spring容器中配置MultipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean>
注意:此处的id必须取multipartResolver这个名字,否则配置无效。
MultipartFile用于接收从页面传过来的文件
MultipartHttpServletRequest可以处理多个上传文件
@RequestMapping(value="upload2",method=RequestMethod.POST) public void upload2(MultipartHttpServletRequest request,HttpServletResponse response){ Iterator<String> itr=request.getFileNames(); while(itr.hasNext()){ MultipartFile myfile=request.getFile(itr.next()); String originName=null; try { originName=new String(myfile.getOriginalFilename().getBytes("iso-8859-1"),"utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String realPath=request.getServletContext().getRealPath("/upload")+"/"+originName; try { myfile.transferTo(new File(realPath));//该方法用于传输文件到指定路径 } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
单个的文件上传把参数MultipartHttpServletRequest改为MultipartFile
@RequestMapping(value="upload",method=RequestMethod.POST) public void upload(MultipartFile myfile,HttpServletRequest request,HttpServletResponse response){
......
}
文件下载
以前的想法,文件下载直接把超链接指定到文件所在位置,但这种方式在某些浏览器行不通。
解决办法是:链接访问后台,由后台处理传输字节流,返回给前台。
@RequestMapping("download") @ResponseBody public void download(HttpServletRequest request,HttpServletResponse response){ String path="1.docx"; String realpath=request.getServletContext().getRealPath("/upload")+"/"+path; File file=new File(realpath); StringBuffer sb=new StringBuffer(); try { FileInputStream fis=new FileInputStream(file); ServletOutputStream out=response.getOutputStream(); byte[] b=new byte[1024]; while(fis.read(b)!=-1){ out.write(b); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
这样就可以处理在任何浏览器中的下载功能。
标签:
原文地址:http://www.cnblogs.com/yxjdragon/p/5939746.html