How does the front end get the filename in the response header Content-Disposition?

question:

When the backend returns the file stream, it puts the file type in the response header, and the frontend needs to manually add the filename suffix after obtaining the filename.

Code:

front end:

downloadFile(response, fileName) {
	const headers = response.headers;
	const contentType = headers['content-type'];
	const blob = new Blob([response.data], { type: contentType });
	const temp = response.headers['content-disposition'];
	let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
	let matches = filenameRegex.exec(temp);
	let fileType = '';
	if (matches != null && matches[1]) {
		fileType = matches['input'].substring(matches['input'].lastIndexOf('.'));
	}
	var downloadElement = document.createElement('a');
	var href = window.URL.createObjectURL(blob); //创建下载的链接
	downloadElement.href = href;
	downloadElement.download = fileName + fileType; //下载后文件名
	document.body.appendChild(downloadElement);
	downloadElement.click(); //点击下载
	document.body.removeChild(downloadElement); //下载完成移除元素
	window.URL.revokeObjectURL(href); //释放掉blob对象
}

rear end:

By default, there are only six simple response headers that can be exposed to the outside:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

You need to add setHeader to the backend to expose Content-disposition for front-end access.

response.setHeader("Access-Control-Expose-Headers", "Content-Disposition")
response.setHeader("Content-Disposition", ...)

Guess you like

Origin blog.csdn.net/jojoyoyo88/article/details/130128787