后端
“Content-Disposition”: “attachment; filename=123.jpeg”
"Content-Type": "image/jpeg",
"Cache-Control": "no-cache",
"Content-Disposition": "attachment; filename=123.jpeg"
前端设计
a标签 :download属性下载
download
属性实现文件下载,直接调用浏览器的下载功能,而且还可以给download属性设置值来规定下载文件的名称,如果在设置值时没有指定文件的扩展名,浏览器将自动检测正确的文件名并添加到文件(.jpg, .pdf, .txt, .html, 等等)。但是存在直接打开文件预览而不是下载问题
<a href="123.jpg" download>下载</a>
URL.createObjectURL() 实现文件下载
1.axios
download(url) {
axios(url, {
responseType: 'blob', //重要代码
}).then(res => {
const contentType = res.headers['content-type'] || 'application/pdf';
let filename = "使用说明文档.pdf"; // 默认文件名
// 根据content-type进行判断
if (contentType.includes('application/pdf')) {
filename = "使用说明文档.pdf";
} else if (contentType.includes('image/jpeg')) {
filename = "图片.jpg";
} else if (contentType.includes('image/png')) {
filename = "图片.png";
} else {
filename = Date.now() + ".unknown";
}
const url = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url); // 释放 URL 对象
}
)
},
2.fetch
function handleFetchClick() {
var url = 'http://127.0.0.1:9090/ceshi/14.jpg'; //http://127.0.0.1:9090/ceshi/14.jpg PvReport.pdf
fetch(url)
.then(response => {
if (response.status == 200) {
// 返回的.blob()为promise,然后生成了blob对象,此方法获得的blob对象包含了数据类型,十分方便
console.log('response', response);
var contentType = response.headers.get('content-type');
console.log(contentType);
return response.blob()
}
}).then(blob => {
console.log(blob);
var element = document.createElement('a');
const blobUrl = URL.createObjectURL(blob)
element.setAttribute('href', blobUrl);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
URL.revokeObjectURL(blobUrl)
})
.catch(error => console.log(error));
}
3.XMLHttpRequest
function handleXHRClick() {
var url = 'http://127.0.0.1:9090/ceshi/14.jpg'; //http://127.0.0.1:9090/ceshi/14.jpg PvReport.pdf
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var blob = xhr.response;
var contentType = xhr.getResponseHeader('Content-Type');
var element = document.createElement('a');
const blobUrl = URL.createObjectURL(blob)
element.setAttribute('href', blobUrl);
element.setAttribute('download', '');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
URL.revokeObjectURL(blobUrl)
}
}
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", 'application/json;charset=utf-8');
xhr.responseType = 'blob';
xhr.send()
}