我正在做一个功能,压缩图像列表并下载它们。我遇到了一个问题,下载花了很长时间。如何提高下载速度?
我的密码
api.php
Route::post('/download-images', [DownloadController::class, 'downloadImages'])->name('api.download.images');
字符串
控制器
public function downloadImages(Request $request)
{
$zipFileName = $this->service->downloadImages($request);
return response()->download($zipFileName, null, ['Content-Type: application/octet-stream','Content-Length: '. filesize($zipFileName)])->deleteFileAfterSend(true);
}
型
服务
public function downloadImages(Request $request)
{
$imageUrls = $request->get('images');
$type = $request->get('type') ?? 'images';
$zip = new ZipArchive();
$zipFileName = $type . '.zip';
$zip = new ZipArchive();
if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
foreach ($imageUrls as $imageUrl) {
$imageContent = file_get_contents($imageUrl);
$filename = basename($imageUrl);
$zip->addFromString($filename, $imageContent);
}
$zip->close();
return $zipFileName;
}
return $zipFileName;
}
型
在客户端,我打电话 AJAX
function downloadImages(eleClass) {
$("div.spanner").addClass("show");
$("div.overlay").addClass("show");
const imageLinks = [];
$('ul.'+ eleClass +' li img').each(function() {
var imageLink = $(this).attr('src');
imageLinks.push(imageLink);
});
if (imageLinks.length == 0) {
$("div.spanner").removeClass("show");
$("div.overlay").removeClass("show");
return;
}
$.ajax({
url: '/api/download-images',
method: 'POST',
data: { images: imageLinks },
xhrFields: {
responseType: 'blob' // Set the response type to 'blob'
},
success: function (data, status, xhr) {
// Handle success, e.g., show a success message
console.log('Images downloaded successfully.');
// Create a temporary anchor element
var downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(data); // Create a Blob URL for the response
downloadLink.download = eleClass + '.zip'; // Set the desired file name
// Programmatically trigger the download
downloadLink.click();
$("div.spanner").removeClass("show");
$("div.overlay").removeClass("show");
},
error: function (xhr, status, error) {
// Handle error, e.g., display an error message
console.error('Error downloading images:', error);
$("div.spanner").removeClass("show");
$("div.overlay").removeClass("show");
}
});
}
型
我在浏览器上看了,花了很长时间才“内容下载”
我正在寻找一个解决方案,以提高文件下载速度。或者另一种压缩图像链接和下载列表的解决方案
1条答案
按热度按时间l2osamch1#
我试着添加头和回调函数来删除发送后的文件,它改善了不少,约12秒
控制器
字符串