zoukankan      html  css  js  c++  java
  • 下载文件默认文件名中文乱码问题的解决

    下载文件默认文件名中文乱码问题的解决一般是因为没有转码导致。

    package sample.server;
    
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gwt.core.client.GWT;
    import com.google.gwt.user.client.ui.Frame;
    
    public class DownloadServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doGet( HttpServletRequest req, HttpServletResponse resp )
    		throws ServletException, IOException
    	{
    		//此函数对应之前的 Frame frame = 
    		//new Frame( GWT.getModuleBaseURL() + "filedownload" + "?id=downloadiframe"+"&filename=" + filename );
    		//传文件名那个简单啊
    		String filename = req.getParameter("filename");
    		
    		//这边你要自己决定从哪下载的文件!! 我是把上传路径直接给他了
    		//这里说下。。我先前没自己创建 uploads 结果十分悲剧
    		//记得在 war 路径下创建 !!
    		String filepath = req.getRealPath("/uploads");
    		File file = new File( filepath+"/"+filename );
    
    
    		FileInputStream fis = new FileInputStream(file);
    		resp.addHeader("Content-Disposition","attachment; filename=" + filename );//此处设置默认下载文件名,如果是中文肯定乱码,需要做一次ULL转码,Server.UrlEncode(filename)
    
    		ServletOutputStream out = resp.getOutputStream();
    		resp.setBufferSize(32768);
    		int bufSize = resp.getBufferSize();
    		byte[] buffer = new byte[bufSize];
    		BufferedInputStream bis = new BufferedInputStream(fis,bufSize);
    
    		int bytes;
    		while ((bytes = bis.read(buffer, 0, bufSize)) >= 0)
    			out.write(buffer, 0, bytes);
    		bis.close();
    		fis.close();
    		out.flush();
    		out.close();
    	}
    }
    


    来源:http://www.cnblogs.com/blogyuan,欢迎转载
  • 相关阅读:
    认识Linux
    Java之安装环境
    Markdown学习
    使用cacti监控linux server的接口流量
    IDRAC安装dell服务器操作系统(linux or windows),用到生命周期管理器
    网络编程--练习题
    linux搭建ntp服务器-添加交换机客户端,windows客户端
    linux centos7搭建redis-5.0.5
    linux centos7搭建mysql-5.7.29
    对称加密与非对称加密
  • 原文地址:https://www.cnblogs.com/blogyuan/p/3082343.html
Copyright © 2011-2022 走看看