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