Java下载文件解决中文乱码问题


直接上代码

	/**
	 * @desc 下载已存在的文件
	 */
	public void sendFile(HttpServletRequest request, HttpServletResponse response, File file, String name) throws IOException {
    	        response.setContentType("application/x-download");
		OutputStream output = response.getOutputStream();
		String filenamedisplay = name;
		response.addHeader("Content-Length",""+file.length());
		
		String userAgent = request.getHeader("User-agent");
		byte[] bytes = userAgent.contains("MSIE") ? name.getBytes() : name.getBytes("UTF-8");
		filenamedisplay = new String(bytes, "ISO-8859-1");  
		response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filenamedisplay));
		int BUFSIZE = 65536;
		FileInputStream fis=null;
		try{
			fis= new FileInputStream(file);
			int s;
			byte[] buf = new byte[BUFSIZE];
			while((s = fis.read(buf))>-1){
				output.write(buf, 0, s);
			}
		}catch (Exception ex) {
				ex.printStackTrace();
		}finally{
			output.flush();
			fis.close();
			output.close();
		}
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM