- @RequestMapping(value="/downloadFile")
- public void downloadFile(String fileName,HttpServletResponse response,HttpServletRequest request)
- {
- response.setCharacterEncoding("utf-8");
- response.setContentType("multipart/form-data");
- response.setContentType("application/octet-stream");
- String filePath=request.getSession().getServletContext().getRealPath("/");
- FileChannel channel=null;
- FileInputStream fis=null;
- try {
- File file=new File(filePath+File.separator+"files"+File.separator+fileName);
- response.setHeader("Content-Disposition", "attachment;fileName="+ java.net.URLEncoder.encode(fileName, "UTF-8"));
- response.setContentLength((int) file.length());
- fis=new FileInputStream(file);
- channel=fis.getChannel();
- ServletOutputStream sos=response.getOutputStream();
- ByteBuffer bytedata = ByteBuffer.allocate(1024);
- while(channel.read(bytedata)!= -1)
- {
- bytedata.flip();
- sos.write(bytedata.array());
- bytedata.clear();
- }
- channel.close();
- fis.close();
- sos.flush();
- } catch (FileNotFoundException e) {
- logger.error("文件不存在",e);
- } catch (IOException e) {
- logger.error("io出错",e);
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/1108201513394.html
来源: http://www.codesnippet.cn/detail/1108201513394.html