沫沫金在解决生成文档的最后,需要实现客户端下载功能。就好好写了一个完善的方法,贡献给大家。
特点:
-中文支持
-全文当支持*.rar,*.zip,*.txt,*.doc
-拷贝后直接使用
提示:
URLEncoder使用Jar包
- import java.net.URLEncoder
解决方案:
- //这么调用sunvinsDown(root+"/",strFileName,response);就好
- public static void sunvinsDown(String filePath,String fileName,HttpServletResponse response)
- throws Exception {
- File file = new File(filePath+fileName);
- if(!file.exists()){
- System.out.println("文件不存在");
- }else{
- FileInputStream fis = new FileInputStream(file);
- BufferedInputStream bis = new BufferedInputStream(fis);
- OutputStream os=response.getOutputStream();
- BufferedOutputStream bos=new BufferedOutputStream(os);
- fileName=URLEncoder.encode(fileName,"UTF-8");
- fileName=new String(fileName.getBytes("UTF-8"),"GBK");
- response.reset();
- response.setContentType("UTF-8");
- response.setContentType("Application/x-msdownload");
- response.setHeader("Content-Disposition", "attachment;filename="+fileName);
- response.setHeader("Content-Length", String.valueOf(bis.available()));
- int bytesRead=0;
- byte[] buffer=new byte[1024];
- while((bytesRead=bis.read(buffer))!=-1){
- bos.write(buffer,0,bytesRead);
- }
- bos.flush();
- bos.close();
- bis.close();
- os.close();
- fis.close();
- }
- }
本文转自 沫沫金 51CTO博客,原文链接:http://blog.51cto.com/zl0828/965197,如需转载请自行联系原作者