文件下載:報錯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
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找 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'. 跨域問題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'. The credentials mode of requests initiated by t 瀏覽器報`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'. `問題的解決方案 When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the "Access-Control-Allow-Origin" response header. java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed a Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' heade has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 跨域請求錯誤: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM