关于下载文件以及在swagger-ui中遇到的坑

由于需求,需要导出一个带有中文名的json文件,之前已经习惯使用swagger-ui这个测试接口了,所以一开始是这样的

 

下载下来的是这种乱码格式的文件,于是乎尝试了这几种:

response.addHeader("Content-Disposition","attachment;fileName=" +new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
response.setHeader("Content-Disposition", "attachment; fileName="+  fileName +";filename*=utf-8''"+URLEncoder.encode(fileName,"UTF-8"));

后来证明这几个带中文都是可以的(谷歌浏览器)

然鹅,当时我通过swagger-ui下载文件还是中文乱码。。。

并且在尝试的过程中还学了一招,之前单纯的通过OutputStream来输出文件,改为了java NIO的Files.copy

代码:

//		FileInputStream in = null;
//		OutputStream out = null;
		try {
			String fileName = "中文_" + name;

//			 response.setContentType("application/force-download");
//			response.setHeader("content-disposition", "attachment;filename="  /*+ new String(fileName.getBytes("UTF-8"),"iso-8859-1"));*/
//			         + URLEncoder.encode(fileName, "iso-8859-1"));
	        
//			in = new FileInputStream(filepath);
//			out = response.getOutputStream();
//			byte buffer[] = new byte[1024];
//			int len = 0;
//			while ((len = in.read(buffer)) > 0) {
//				out.write(buffer, 0, len);
//			}
	        
	        Path file = Paths.get(JSONPATH, name);
	        if (Files.exists(file)) {
	        	response.setContentType("application/force-download");
     //	如果文件名有中文的话,进行URL编码,让中文正常显示
	response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
	            try {
	                Files.copy(file, response.getOutputStream());
	            } catch (IOException ex) {
	            }
	        }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
//			try {
//				in.close();
//				out.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}

		}

OutputStream已经被我注释了,根据自需来扣代码

后来查询了(谷歌)好几篇文章,脑袋灵光一闪,我直接在地址栏输入:

然后...

ok,完工,告辞!

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值