文件下载:报错The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'
前言:这篇文件下载的后台代码太繁琐,建议参考https://www.cnblogs.com/zwh0910/p/13745947.html
前端:
<el-button
type="primary"
icon="el-icon-download"
@click="downloadTemplate('药品清单-模板.xlsx')">下载模板</el-button>
在main.js中:
import fileDownload from 'js-file-download'
Vue.prototype.downloadTemplate = function (templateName) {
const fileEntity = {
fileName: templateName,
filePath: "D:\\prism\\svn\\drug-question\\drugques-pc\\src\\template\\"+templateName,
downloadChannel: 'DIR'
}
medicineListApi.ptsFileDownload(fileEntity).then(response => {
fileDownload(response.data, templateName)
}).catch(error => {
console.log(error)
})
}
在package.json中添加依赖版本
"dependencies": {
"@aximario/json-tree": "^2.1.0",
"axios": "^0.19.0",
"core-js": "^2.6.5",
"echarts": "^4.2.1",
"element-ui": "^2.13.2",
"js-file-download": "^0.4.4",
},
如果是下载本地的文件,则应写详细的路径:D:\prism\svn\drug-question\drugques-pc\src\template
在medicineList.js中
const baseUrl = "/medicineList"
ptsFileDownload(query) {
return request({
url: baseUrl +'/fileDownload',
method: 'post',
data: query,
responseType: 'arraybuffer'
})
},
后台代码:
controller:
@RequestMapping(value = "/fileDownload", method = { RequestMethod.POST, RequestMethod.GET })
public String fileDownload(@RequestBody(required=true) PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
medicineListService.fileDownload(fileEntity, response);
return null;
}
service接口
public interface MedicineListService extends IService<DrugData> {
void fileDownload(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception;
}
service实现类
@Override
public void fileDownload(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
String fileName = fileEntity.getFileName();
if (null == fileName || ("").equals(fileName.trim())) {
logger.error("No FileName Found.");
throw new Exception("No FileName Found.");
}
String downloadChannel = fileEntity.getDownloadChannel();
if (null == downloadChannel || ("").equals(downloadChannel.trim())) {
logger.error("Need to identity download channel.");
throw new Exception("Need to identity download channel.");
}
if (CHANNEL_DIR.equalsIgnoreCase(downloadChannel)) {
this.downloadFromDir(fileEntity, response);
} else if (CHANNEL_URL.equalsIgnoreCase(downloadChannel)) {
this.downloadFromUrl(fileEntity, response);
}
}
/**
* 从URL地址下载
*
* @param fileEntity
* @param response
* @throws Exception
*/
private void downloadFromUrl(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
String filePath = fileEntity.getFilePath();
String serverFilePath = fileEntity.getServerFilePath();
if ((null == filePath || ("").equals(filePath.trim())) && (null == serverFilePath || ("").equals(serverFilePath.trim()))) {
logger.error("No FilePath Found.");
throw new Exception("No FilePath Found.");
}
String realFilePath = (null == filePath || ("").equals(filePath.trim())) ? serverFilePath : filePath;
logger.info("Begin download file from Url: " + realFilePath);
try {
URL url = new URL(realFilePath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] srcBytes = readInputStream(inputStream);
this.download(fileEntity, response);
} catch (IOException e) {
e.printStackTrace();
throw new Exception(e);
}
}
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
/**
* 创建临时文件
*
* @param fileEntity
* @param srcBytes
*/
public void downloadFromDir(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
String filePath = fileEntity.getFilePath();
String serverFilePath = fileEntity.getServerFilePath();
if ((null == filePath || ("").equals(filePath.trim())) && (null == serverFilePath || ("").equals(serverFilePath.trim()))) {
logger.error("No FilePath Found.");
throw new Exception("No FilePath Found.");
}
String realFilePath = (null == filePath || ("").equals(filePath.trim())) ? serverFilePath : filePath;
logger.info("Begin download file from Directory: " + realFilePath);
fileEntity.setRealFilePath(realFilePath);
try {
// 以流的形式下载文件。
InputStream fis;
fis = new BufferedInputStream(new FileInputStream(realFilePath));
byte[] srcBytes = new byte[fis.available()];
fis.read(srcBytes);
fis.close();
this.download(fileEntity, response);
} catch (IOException ex) {
ex.printStackTrace();
throw new Exception(ex);
}
}
/**
* 拼接response header 并已流的形式下载文件
*
* @param fileEntity
* @param response
* @throws Exception
*/
public void download(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
String fileName = fileEntity.getFileName();
String realFilePath = fileEntity.getRealFilePath();
File file = new File(realFilePath);
try {
// 以流的形式下载文件。
InputStream fis;
fis = new BufferedInputStream(new FileInputStream(realFilePath));
byte[] srcBytes = new byte[fis.available()];
fis.read(srcBytes);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");//设置编码集,文件名不会发生中文乱码
response.setContentType("application/force-download");//
response.setHeader("content-type", "application/octet-stream");
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes(), "utf-8"));// 设置文件名
response.addHeader("Content-Length", "" + file.length());
response.setHeader("Access-Control-Allow-Origin", "*");
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(srcBytes);
toClient.flush();
toClient.close();
} catch (IOException ex) {
throw new Exception(ex);
}
}
如果报错:The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'
解决:将request.js中的withCredentials由true改为false
const service = axios.create({
baseURL: "http://localhost:8080/drugques",
withCredentials: false,
timeout: 150000
});
文件下载:报错The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'的更多相关文章
- 微信小程序WebSocket报错:Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was ...
- python webdriver 报错WebDriverException: Message: can't access dead object的原因(pycharm中)
PyCharm中运行firefox webdriver访问邮箱添加通讯录的时候报错-WebDriverException: Message: can't access dead object 调了半天 ...
- 【Mac 10.13.0】安装 libimobiledevice,提示报错:warning: unable to access '/Users/lucky/.config/git/attributes': Permission denied解决方案
打开终端,执行命令: 1.sudo chown -R XXX /usr/local (XXX表示当前用户名) 2.ruby -e "$(curl -fsSL https://raw.git ...
- mysql忘记root密码或报错:ERROR 1044 (42000): Access denied for user ”@’localhost’ to database ‘xx‘
有的时候忘记了root密码或其他用户的密码,登录的时候报错:ERROR 1044 (42000): Access denied for user ”@’localhost’ to database ' ...
- Access control allow origin 简单请求和复杂请求
原文地址:http://blog.csdn.net/wangjun5159/article/details/49096445 错误信息: XMLHttpRequest cannot load http ...
- Ubuntu下MySQL报错:ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
在Ubuntu下 想要登录mysql数据库 root@JD:~# mysql -uroot -p 报错 ERROR 1045 (28000): Access denied for user 'root ...
- 【问题与解决】Mac OS通过 npm 安装 React Native 报错(checkPermissions Missing write access to /usr/local/lib/node_modules)
报错情况: 当Mac OS通过 npm 安装 React Native 报错,警告文字为:checkPermissions Missing write access to /usr/local/lib ...
- 报错:PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\Anaconda3\\Lib\\site-packages\\pywebhdfs'
Outline 在本(Windows系统)地往 “PAI”(hdfs)上上传数据时,需要安装pywebhdfs包,然后就报错了: 报错信息: PermissionError: [WinError 5] ...
- CM使用MySQL数据库预处理scm_prepare_database.sh执行报错:java.sql.SQLException: Access denied for user 'scm'@'hadoop101.com' (using password: YES)
1.报错提示: [root@hadoop101 ~]# /opt/module/cm/cm-/share/cmf/schema/scm_prepare_database.sh mysql cm -hh ...
随机推荐
- Java-eclipse导入jar包
Java-eclipse导入jar包 方法一:基本步骤式 右键项目属性,选择Property,在弹出的对话框左侧列表中选择Java Build Path,如下图所示:选择Add External JA ...
- 使用Selenium截取网页上的图片
前言 同样是为了刷课,没想到工作后依然和大学一样逃脱不了需要刷网课的命运-- 正文 直接说干货了,截取图片,需要截取的图片是什么图片大家都懂(说的就是你,验证码),其他图片的话不需要截取,直接拿到地址 ...
- linux 一分钟搭建zookeeper linux 单机版(亲测可用)
wget https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper-3.4.14/zookeeper-3.4.14.tar.gzt ...
- Codeforces Round #594 (Div. 2) D1 - The World Is Just a Programming Task (贪心)
思路:枚举换的位置i,j 然后我们要先判断改序列能否完全匹配 如果可以 那我们就需要把差值最大的位置换过来 然后直接判断就行
- CF-1328 E. Tree Queries
E. Tree Queries 题目链接 题意 给定一个树,每次询问一组点,问是否存在一条从根到某点的路径,使得该组点到该路径的最短距离不超过1 分析 从根到达某点的路径,如果覆盖到了某个点,那么一定 ...
- bzoj1500: [NOI2005]维修数列 (Splay+变态题)
Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 11353 Solved: 3553 [Submit][Status][Discuss] Descrip ...
- Codeforces Round #648 (Div. 2) B. Trouble Sort
一开始读错题了...想当然地认为只能相邻元素交换...(然后换了两种写法WA了4发,5分钟切A的优势荡然无存) 题目链接:https://codeforces.com/contest/1365/pro ...
- hdu 1045 Fire Net 二分图匹配 && HDU-1281-棋盘游戏
题意:任意两个个'车'不能出现在同一行或同一列,当然如果他们中间有墙的话那就没有什么事,问最多能放多少个'车' 代码+注释: 1 //二分图最大匹配问题 2 //难点在建图方面,如果这个图里面一道墙也 ...
- Hyper-V安装CentOS修改分辨率
grubby --update-kernel=ALL --args="video=hyperv_fb:1600x900" reboot https://blog.csdn.net/ ...
- PowerShell启用多跳远程控制
有些场景下,我们使用远程连接了某个Server,在远程Server中再想进行远程操作,就会提示错误.因为默认的认证信息只会传递一跳. 对此,微软官方文档给出的解决方案是:https://docs.mi ...