简体   繁体   English

使用JavaScript和PHP下载图像文件并返回zip文件

[英]Using JavaScript and PHP to download image files and return a zip file

I'm in the middle of developing a Safari extension for imageboard-type websites and one of the bigger features I'm hoping to implement is the ability to download all of the images (the posted ones, not the global page-level images) that had been posted. 我正在为图像板型网站开发Safari扩展,而我希望实现的更大功能之一就是能够下载所有图像(已发布的图像,而不是全局页面级图像)的功能。已发布。

There are similar questions here already, but mine differs a bit in that the images in question are hosted on an entirely different server. 这里已经存在类似的问题,但是我的问题有所不同,这些问题的图像托管在完全不同的服务器上。 I've been brainstorming a bit and figured that gathering all of the image URLs in a JS array then sending it to my server to be turned into a zip file (forcing the download, not just a link to the file) would be the best way to go. 我一直在集思广益,发现将所有图像URL收集到JS数组中,然后将其发送到服务器以转换为zip文件(强制下载,而不仅仅是链接到文件)是最好的。要走的路。 I also want the zip to be deleted after the user downloads it. 我还希望用户下载后将其删除。

I've already finished the majority of the extension features but this one is stumping me. 我已经完成了大多数扩展功能,但是这一功能让我很沮丧。 Any help would be greatly appreciated. 任何帮助将不胜感激。

How would I'd go about doing this? 我将如何去做呢?

You want a extension to contact your server for downloads? 您是否希望扩展程序与您的服务器联系以进行下载? That's a terrible idea! 这是一个可怕的主意! Make the zipfile locally - it's not regular javascript, it's an extension - you have full access. 在本地制作zip文件-这不是常规的javascript,而是扩展名-您具有完全访问权限。

Anyway assuming you want to do this anyway, what is the trouble you are having? 无论如何,假设您仍然想这样做,那么您遇到的麻烦是什么? You get a list of urls, send them to your server, your server downloads them, zips them and send them to the user. 您将获得URL列表,将其发送到服务器,服务器将其下载,压缩并发送给用户。 (The "your server downloads them" part should worry you!) (“您的服务器下载它们”部分应该让您担心!)

What problem are you having? 你有什么问题

You can use PHP's ZipArchive class to make a ZIP, then stream it to the browser. 您可以使用PHP的ZipArchive类制作ZIP,然后将其流式传输到浏览器。

<?php
// Create temp zip file
$zip = new ZipArchive;
$temp = tempnam(sys_get_temp_dir(), 'zip');
$zip->open($temp);

// Add files
$zip->addFromString('file.jpg', file_get_contents('http://path/to/file.jpg'));
$zip->addFile('/this/is/my/file.txt');

// Write temp file
$zip->close();

// Stream file to browser
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=myFile.zip');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($temp));

readfile($temp);

unlink($temp);
exit;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM