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();
		}
    }

猜你喜欢

转载自www.cnblogs.com/jimmyshan-study/p/11645204.html