Ajax Safari下载blob文件作为example.com
我正在使用Ajax POST请求生成PDF文档并将其发送给用户。在Chrome、Edge、Firefox中一切正常,但Mac和IPhone上的Safari会以example.com的形式下载该文件 我正在使用我发现的以下功能:Ajax Safari下载blob文件作为example.com,ajax,safari,Ajax,Safari,我正在使用Ajax POST请求生成PDF文档并将其发送给用户。在Chrome、Edge、Firefox中一切正常,但Mac和IPhone上的Safari会以example.com的形式下载该文件 我正在使用我发现的以下功能: function downloadFile(data, filename, mime) { // It is necessary to create a new blob object with mime-type explicitly set
function downloadFile(data, filename, mime) {
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
const blob = new Blob([data], {type: mime || 'application/octet-stream'});
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE doesn't allow using a blob object directly as link href.
// Workaround for "HTML7007: One or more blob URLs were
// revoked by closing the blob for which they were created.
// These URLs will no longer resolve as the data backing
// the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
return;
}
// Other browsers
// Create a link pointing to the ObjectURL containing the blob
const blobURL = window.URL.createObjectURL(blob);
const tempLink = document.createElement('a');
tempLink.setAttribute('download', filename);
tempLink.style.display = 'none';
tempLink.href = blobURL;
// Safari thinks _blank anchor are pop ups. We only want to set _blank
// target if the browser does not support the HTML5 download attribute.
// This allows you to download files in desktop safari if pop up blocking
// is enabled.
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
setTimeout(() => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(blobURL);
}, 500);
}
这是ajax请求:
$.ajax({
url: '{{ path('create_list') }}',
data: data,
processData: false,
contentType: false,
cache: false,
type: 'post',
enctype: 'multipart/form-data',
xhrFields: {
responseType: 'blob'
},
success: function(data, status, xhr) {
model.isCreating(false);
let date = new Date();
let name = `${model.wineList.companyName() }
_${date.getHours()}
_${date.getMinutes()}
_${date.getSeconds()}.pdf`;
downloadFile(data, name, 'application/pdf')
Swal.close();
{% if app.debug %}
console.log(data);
{% endif %}
-----------
我检查了Safari属性,但出于某种原因忽略了它
知道问题出在哪里吗?问题出在这一行:
let name = `${model.wineList.companyName() }
_${date.getHours()}
_${date.getMinutes()}
_${date.getSeconds()}.pdf`;
由于某些原因,换行符使Safari恢复到example.com,忽略名称