後臺推送文件給瀏覽器下載方法

private void pushFile(File file, HttpServletResponse resp) throws IOException {
		String fileName = file.getName();
		InputStream is = null;
		ServletOutputStream os = null;
		try {
			fileName = URLEncoder.encode(fileName,"UTF-8");
			resp.reset();//清空輸出流
			resp.setContentType("multipart/form-data");//定義輸出類型
	        resp.setHeader("Content-disposition", "attachment; filename=\""+fileName+"\"");//設定輸出文件頭
	        is = new FileInputStream(file);
	        os = resp.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while((length = is.read(b))>0) {
				os.write(b, 0, length);
			}
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			is.close();
			os.close();
		}
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章