Symfony2:如何使用Ajax强制下载多个图像在一个zip文件中
这是我的AJAX请求:
function DownloadZip() { var searchIDs = $("#image_id:checked").map(function(){ return $(this).val(); }).get(); $.ajax( { type:'POST', url: $('#admin_product_zip').text(), data: {searchIDs:searchIDs}, success: function(response) { } } ); return false; }
这是我的控制器方法,我得到产品ID并从数据库中获取这些id,获取正确的图像路径:
public function zipMultipleDownload($data){ foreach($data as $product_ind) { $product = $this->repo->find(3); $images=$product->getColorImagesPaths(); $itemImages=$product->getItemImagesPaths(); $archive_file_name =$product->getName().$product->getId().'.zip'; //print_r($itemImages); //return new response('test'); } $this->zipFilesAndDownload($images,$archive_file_name,$itemImages); //return json_encode($itemImages); } // Function for dowloading images in zip format public function zipFilesAndDownload($file_names,$archive_file_name,$itemImages) { $zip = new ZipArchive(); if ($zip->open($archive_file_name, \ZIPARCHIVE::CREATE | \ZIPARCHIVE::OVERWRITE) === TRUE) { foreach ($file_names as $files) { // $zip->addFile("uploads/ltf/products/display/web/5232f56d0291a.png","uploads/ltf/products/display/web/5232f56d0291a.png"); $zip->addFile($files['web'], $files['web']); $zip->addFile($files['iphone'], $files['iphone']); } foreach ($itemImages as $itemfiles) { $zip->addFile($itemfiles['web'],$itemfiles['web']); $zip->addFile($itemfiles['iphone4s'], $itemfiles['iphone4s']); $zip->addFile($itemfiles['iphone5'], $itemfiles['iphone5']); } $zip->close(); } else { return "can not open"; } $response =new Response(); //then send the headers to foce download the zip file $response->headers->set('Content-Type','application/zip'); $response->headers->set('Content-Disposition', 'attachment; filename="' . basename($archive_file_name) . '"'); $response->headers->set('Pragma', "no-cache"); $response->headers->set('Expires', "0"); $response->headers->set('Content-Transfer-Encoding', "binary"); $response->sendHeaders(); $response->setContent(readfile($archive_file_name)); return $response; }
问题:这是获取二进制数据,特殊字符而不是图像。
图像路径是适当的。
你加了用吗?
use ZipArchive;
在您的控制器中,并尝试这一个
$response = new Response(); // Set headers $response->headers->set('Cache-Control', 'private'); $response->headers->set('Content-type', mime_content_type($filename)); $response->headers->set('Content-Disposition', 'attachment; filename="' . basename($filename) . '"'); $response->headers->set('Content-length', filesize($filename)); // Send headers before outputting anything $response->sendHeaders(); $response->setContent(file_get_contents($filename));
如果仍然严格的事情,那么尝试删除sendHeaders