我有一个页面,用户可以下载他要求的格式的图片,请求被发送到一个PHP脚本,产生的图像和...... 这是在StackOverflow上找到的JQUERY代码。
$('[name ="download_img_ajax"]').click(function(e){
e.preventDefault()
var element = this
var formdata = new FormData(element.closest(".form_downIMG"))
formdata.append('download_img_ajax','true')
$(this).next("span.down_response").html('Preparazione file in corso...'),
$('.emailadr').hide(),
$.ajax({
type: 'POST',
url: '$target_post',
data: formdata,
cache: false,
contentType: false,
processData: false,
success: function(tornato) {
const blob = new Blob([tornato], {type: 'image/jpeg'});
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = "file.jpg";
document.body.appendChild(a);
a.click();
},
})
})
PHP脚本将文件生成为一个临时文件($img),但我不明白如何将其返回为一个正确的AJAX响应。
echo fread($img,filesize($img_path));
即使文件的大小是正确的,也不能工作(文件没有被识别为JPG文件)。
在一个正常的表单中,我以这种方式返回文件。
header('Content-Transfer-Encoding: binary'); // For Gecko browsers mainly
header('Accept-Ranges: bytes'); // For download resume
header('Content-Length: ' . filesize($img_path)); // File size
header('Content-Encoding: none');
header('Content-Type: image/jpeg'); // Change this mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $imgID); // Make the browser display the Save As dialog
readfile($img_path);
fclose($img);
PS:在JQ中,我使用了next,closeest等,因为我有很多表单都是由PHP动态生成的。
我只对大约700KB的文件使用这种下载方式,把更大的文件留在老方法的提交表单上,在PHP中使用target="_blank "和readfile。安全吗?
如果我想管理错误(例如PHP脚本不能提供文件),我如何处理?
谢谢。
解决了FileSaver.js的问题( https:/github.comeligreyFileSaver.js。 )
var xhr = new XMLHttpRequest()
xhr.open('POST', '$target_post')
xhr.responseType = 'blob'
xhr.onload = function() {
saveAs(xhr.response, 'immagine.jpg');
}
xhr.send(formdata)
的PHPecho fread($img,filesize($img_path));