springcloud 通过后端去下载和预览文件,要重设跨域允许
2021-07-11 15:07
标签:res use 方式 程序 orm wow gecko lse reset springcloud 通过后端去下载和预览文件,要重设跨域允许 标签:res use 方式 程序 orm wow gecko lse reset 原文地址:https://www.cnblogs.com/keepMoveForevery/p/9550114.html@RequestMapping("/download")
public void downloadNet(String uri, boolean isOnLine, HttpServletResponse response) throws MalformedURLException {
// 下载网络文件
InputStream inStream = null;
OutputStream fs = null;
URL url = new URL(uri);
String filename = uri.substring(uri.lastIndexOf("/") + 1);
try {
URLConnection conn = url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
inStream = new BufferedInputStream(conn.getInputStream());
int len = 0;
response.reset();
if (isOnLine) { // 在线打开方式
response.setContentType(conn.getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + filename);
response.setHeader("Access-Control-Allow-Origin", cors);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", corsHeader);
response.setHeader("Vary", "Origin");
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
response.setHeader("Access-Control-Allow-Origin", cors);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", corsHeader);
response.setHeader("Vary", "Origin");
}
fs = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
while ((len = inStream.read(buffer)) > 0)
fs.write(buffer, 0, len);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != inStream) {
try {
inStream.close();
} catch (IOException e) {
}
}
if (null != fs) {
try {
fs.close();
} catch (IOException e) {
}
}
}
}
文章标题:springcloud 通过后端去下载和预览文件,要重设跨域允许
文章链接:http://soscw.com/index.php/essay/103762.html