java中下载文件写法之一

没什么想说的。。。。。。。。

@RequestMapping(value="download",method = RequestMethod.GET)
	public void downloadFileAction(HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		response.setCharacterEncoding(request.getCharacterEncoding());//设置编码
		System.out.println(request.getCharacterEncoding());
		response.setContentType("application/octet-stream;charset=utf-8");//内容为二进制流。
		FileInputStream fis = null;//输入流
		try {
			File file = new File("C:\\Users\\YangWenHui\\Desktop\\杂物\\表名.txt");
			fis = new FileInputStream(file);//写入下载文件的路径
//			response.addHeader("Content-Type", "");
			response.setHeader("Content-Disposition", "attachment; filename="+new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));//设置下载文件中有中文名称的
			System.out.println(file.getName());
//			IOUtils.copy(fis,response.getOutputStream());
//			response.flushBuffer();
			BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
			BufferedInputStream bis = new BufferedInputStream(fis);
			
			int length = 0;  
            byte[] temp = new byte[1 * 1024 * 10];//一次读取多大
            while((length = bis.read(temp)) != -1) {//读取文件
            	bos.write(temp, 0, length);
            }
            bos.flush();  
            bis.close();
            bos.close();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			fis.close(); 
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_36956154/article/details/80103384
今日推荐