我正在尝试将一些图像压缩为用户选择。现在我已经想出了一个解压缩的解决方案。我的问题是我将相关数据压缩到zip文件后如何通过browser.i下载它我尝试过不同的方法仍然无法正常工作。当我创建zip时,它存储在公共文件夹中。我可以通过浏览器从那里下载zip文件吗?
这是我的代码
$photos = json_decode(Input::get('photos'));
$dir = time();
foreach ($photos as $file) {
/* Log::error(ImageHandler::getUploadPath(false, $file));*/
$imgName = last(explode('/', $file));
$path = public_path('downloads/' . $dir);
if (!File::exists($path)) {
File::makeDirectory($path, 0775, true);
}
ImageHandler::downloadFile($file, $path . '/' . $imgName);
}
$rootPath = realpath($path);
$zip_file = 'Photos.zip';
$public_dir = public_path();
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file1) {
// Skip directories (they would be added automatically)
if (!$file1->isDir()) {
// Get real and relative path for current file
$filePath = $file1->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
$fileurl = public_path()."/Photos.zip";
if (file_exists($fileurl))
{
return Response::download($fileurl, 'Photos.zip', ['Content-Length: '. filesize($fileurl)]);
} else {
exit('Requested file does not exist on our server!');
}
答案 0 :(得分:2)
问题是您是否正在尝试通过AJAX加载文件,而您无法按照您尝试的方式执行此操作。
if (file_exists($fileurl)) {
return Response::download($fileurl, 'Photos.zip', array('Content-Type: application/octet-stream','Content-Length: '. filesize($fileurl)))->deleteFileAfterSend(true);
} else {
return ['status'=>'zip file does not exist'];
}
将 javascript 更改为:
let xhr = new XMLHttpRequest(), self = this;
window.location = window.location.origin+'/download-file/' + this.selected
希望这能帮到你!
答案 1 :(得分:0)
尝试更改
return Response::download($fileurl, 'Photos.zip', ['Content-Length: '. filesize($fileurl)]);
到
return Response::download($fileurl, 'Photos.zip', array('Content-Type: application/zip','Content-Length: '. filesize($fileurl)));
OR
return Response::download($fileurl, 'Photos.zip', array('Content-Type: application/octet-stream','Content-Length: '. filesize($fileurl)));
答案 2 :(得分:0)
$fileurl = public_path()."/Photos.zip";
if (file_exists($fileurl))
{
return response()->json($fileurl);
}
else
{
exit('Requested file does not exist on our server!');
}
然后添加此行
success: function (data) {
'download': data.fileurl,
}