I am trying to download the zip file with many images.This code is working when i call the path in browser but not downloading when i call from Jquery ajax.Need to change or add anything in header?please help.
Controller:
public function actionZipdownload(){
$files = Yii::$app->request->post('imgsrc');
//it displays the URLs.
$zip = new \ZipArchive();
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
foreach ($files as $file) {
$download_file = file_get_contents($file);
$zip->addFromString(basename($file), $download_file);
}
$zip->close();
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
}
Jquery:
$.ajax({
url:url+'site/zipdownload',
data:{'imgsrc':imgsrc},
type:'POST',
success:function(data){
//alert(data);
}
});
In console response:
I just ignore the Jquery Ajax and done it by Html::a with two actions..When i am calling the url in a tag then the file got downloaded.And also done some changes in controller.
Views:
<?=Html::a('Create Zip',['site/zipdownload'],['class'=>'btn btn-danger pull-left'])?>
<?=Html::a('Download',['site/download'],['class'=>'btn btn-danger pull-left'])?>
Controller:
public function actionZipdownload(){
$files = Yii::$app->request->post('img_src');
$zip = new \ZipArchive();
$tmp_file = 'uploads/images.zip';
if(file_exists($tmp_file)){
$zip->open($tmp_file, ZipArchive::OVERWRITE);
}
else{
$zip->open($tmp_file, ZipArchive::CREATE);
}
$i=1;
foreach ($files as $file) {
$download_file = file_get_contents($file);
$fileParts = pathinfo($file);
$filename = $i.explode("?",$fileParts['filename'])[0];
$zip->addFromString($filename, $download_file);
$i++;
}
$zip->close();
}
public function actionDownload(){
$path = 'uploads/images.zip';
if(file_exists($path)){
\Yii::$app->response->sendFile($path)->send();
unlink($path);
}
else{
return $this->redirect(['site/dashboard']);
}
}
Related
I have to make 3 buttons. On button click I want to download all files from selected folder with correct extension in zip file. Eveything on wordpress site. The problem is, zip file is saving as .zip, but when I open it in notepad, there's HTML code. Thanks for help!
<?php
if(isset($_POST['3dsdownload'])) {dddownloads();}
function dddownloads(){
$dir = realpath("/autoinstalator/wordpress/wp-content/uploads/");
$scan_arr = scandir($dir);
$zip = new ZipArchive();
$zip->open('3ds.zip', ZipArchive::CREATE);
$files = array_diff($scan_arr, array('.','..') );
foreach ($files as $name => $file) {
if (!is_dir($file)){
$filePath = $dir.$file;
$file_ext = pathinfo($filePath, PATHINFO_EXTENSION);
if ($file_ext=="3ds" || $file_ext=="3DS") {
$zip->addFile($filePath, basename($filePath));
}
}
}
$zip->close();
header('Content-disposition: attachment; filename=3ds.zip');
header('Content-type: application/zip');
readfile('3ds.zip');
exit;
}
?>
<form method="post">
<input type="submit" name="3dsdownload"
value="3dsdownload"/>
</form>
The problem was buffer and path. After adding ob_clean() and fixing path, everything works fine! Final code:
<?php //Strona z pobieraniem wszystkich plikow z podziaĆem na formaty
//3ds
if(isset($_POST['3dsdownload'])) {dddownloads();}
function dddownloads(){
ob_clean();
$dir = (dirname(__DIR__,2)."/uploads/");
$scan_arr = scandir($dir);
$zip = new ZipArchive();
$zip->open('3ds.zip', ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE);
$files = array_diff($scan_arr, array('.','..') );
foreach ($files as $name => $file) {
if (!is_dir($file)){
$filePath = $dir.$file;
$file_ext = pathinfo($filePath, PATHINFO_EXTENSION);
if ($file_ext=="3ds" || $file_ext=="3DS") {
$zip->addFile($filePath, basename($filePath));
}
}
}
$zip->close();
header('Content-disposition: attachment; filename=3ds.zip');
header('Content-type: application/zip');
header("Content-Transfer-Encoding: binary");
ob_end_clean();
readfile('3ds.zip');
exit;
}
?>
I Have been reading many similar problems but I just can't find the solution to mine.
All I need is zip the files that come in the POST variable as an array and get the path to the zip file just created. Here is my code... I keep getting an empty Object and just can't make 1 file inside
function downloadAllImages(){
$data = array();
$files = $_POST['files_to_download'];
$archive_file_name = 'images.zip';
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
$data['debug'].=("cannot open <$archive_file_name>\n");
}
//add each files of $file_name array to archive
foreach($files as $file)
{
$zip->addFile($file, basename($file));
}
$zip->close();
//then send the headers to foce download the zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
$data['debug'].=print_r($zip,true);
echo json_encode($data);
die();
}
I'm using JQuery to get the download link after the file is zipped. I just can't make the files to zip.
The array files_to_download prints:
Array(
[0] => http://localhost/br/wp-content/uploads/2020/04/rabbit-black-transp-300x300.png
[1] => http://localhost/br/wp-content/uploads/2020/04/bg-shop-300x169.png
)
And my jQuery
function downloadAllImages(){
var files_to_download = [];
$("img.downloadable").each(function(){
files_to_download.push($(this).attr('src'));
});
jQuery.ajax({
url: runAJAX.ajaxurl,
data: ({action: 'downloadAllImages', files_to_download:files_to_download}),
method: "POST",
success: function(data_received) {
displayAjaxResponse(data_received);
}
});
}
In the end a friend of mine helped and the PHP code should look like this:
function downloadAllImages()
{
$data = array();
$files = $_POST['files_to_download']; // array
$domain= wp_upload_dir();
// used this to rename the file so each post gets it's own zip
$prefix=$_POST['file_prefix'];
$zip = new ZipArchive();
$tmp_zip = $zip->open($domain['basedir'].'/'.$prefix.'images.zip', ZipArchive::CREATE);
foreach($filesas $img)
{
if(!empty($img))
{
$download_file = file_get_contents($img);
$zip->addFromString(basename($img), $download_file);
}
}
$zip->close();
$now = new DateTime();
$data['file'] = get_bloginfo('wpurl')."/wp-content/uploads/{$prefix}images.zip?v={$now ->getTimestamp()}";
echo json_encode($data);
die();
}
And the jQuery looks pretty much the same, except for adding the 'file_prefix' variable.
I am using the ZipArchive class to create a ZIP file and stream it to the client but all archives are not generated correctly.
Any suggestions?
<?php
if(file_exists('../../../thure/uploads/nestingen/58861.pdf'))
{
$files = array('../../../thure/uploads/nestingen/58861.pdf');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
exit;
}
else
{
echo 'file not found';
}
?>
Function (writed by David)
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
Sample Usage
$files_to_zip = array(
'file1',
'file2',
'file3'
);
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');
i am trying to create a zip file(using php) for this i have written the following code:
$fileName = "1.docx,2.docx";
$fileNames = explode(',', $fileName);
$zipName = 'download_resume.zip';
$resumePath = asset_url() . "uploads/resume/";
//http://localhost/mywebsite/public/uploads/resume/
$zip = new ZipArchive();
if ($zip->open($zipName, ZIPARCHIVE::CREATE) !== TRUE) {
echo json_encode("Cannot Open");
}
foreach ($fileNames as $files) {
$zip->addFile($resumePath . $files, $files);
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=".$zipName."");
header("Content-length: " . filesize($zipName));
header("Pragma: no-cache");
header("Expires: 0");
readfile($zipName);
exit;
however on a button click i am not getting anything..not even any error or message..
any help or suggestion would be a great help for me.. thanks in advance
Why not use the Zip Encoding Class in Codeigniter - it will do this for you
$name = 'mydata1.txt';
$data = 'A Data String!';
$this->zip->add_data($name, $data);
// Write the zip file to a folder on your server. Name it "my_backup.zip"
$this->zip->archive('/path/to/directory/my_backup.zip');
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download('my_backup.zip');
https://www.codeigniter.com/user_guide/libraries/zip.html
... it work for me
public function downloadall(){
$createdzipname = 'myzipfilename';
$this->load->library('zip');
$this->load->helper('download');
$cours_id = $this->input->post('todownloadall');
$files = $this->model_travaux->getByID($cours_id);
// create new folder
$this->zip->add_dir('zipfolder');
foreach ($files as $file) {
$paths = 'http://localhost/uploads/'.$file->file_name.'.docx';
// add data own data into the folder created
$this->zip->add_data('zipfolder/'.$paths,file_get_contents($paths));
}
$this->zip->download($createdzipname.'.zip');
}
What is asset_url() function? Try to use APPPATH constant istead this function:
$resumePath = APPPATH."../uploads/resume/";
Add "exists" validation for file names:
foreach ($fileNames as $files) {
if (is_file($resumePath . $files)) {
$zip->addFile($resumePath . $files, $files);
}
}
Add exit() after:
echo json_encode("Cannot Open");
Also I think it's the better desision to use CI zip library User Guide. Simple example:
public function generate_zip($files = array(), $path)
{
if (empty($files)) {
throw new Exception('Archive should\'t be empty');
}
$this->load->library('zip');
foreach ($files as $file) {
$this->zip->read_file($file);
}
$this->zip->archive($path);
}
public function download_zip($path)
{
if (!file_exists($path)) {
throw new Exception('Archive doesn\'t exists');
}
$this->load->library('zip');
$this->zip->download($path);
}
Below scripting working ok in my local system. 1st remove asset_url() from $resumePath and set zip file store location relative path.
- Pass zip file name with its location path to $zip->open()
$fileName = "1.docx,2.docx";
$fileNames = explode(',', $fileName);
$zipName = 'download_resume.zip';
$resumePath = "resume/";
$zip = new ZipArchive();
if ($zip->open($resumePath.$zipName, ZIPARCHIVE::CREATE) !== TRUE) {
echo json_encode("Cannot Open");
}
foreach ($fileNames as $files) {
$zip->addFile($files, $files);
}
$zip->close();
/* create zip folder */
public function zip(){
$getImage = $this->cart_model->getImage();
$zip = new ZipArchive;
$auto = rand();
$file = date("dmYhis",strtotime("Y:m:d H:i:s")).$auto.'.zip';
if ($zip->open('./download/'.$file, ZipArchive::CREATE)) {
foreach($getImage as $getImages){
$zip->addFile('./assets/upload/photos/'.$getImages->image, $getImages->image);
}
$zip->close();
$downloadFile = $file;
$download = Header("Location:http://localhost/projectname/download/".$downloadFile);
}
}
model------
/* get add to cart image */
public function getImage(){
$user_id = $this->session->userdata('user_id');
$this->db->select('tbl_cart.photo_id, tbl_album_image.image as image');
$this->db->from('tbl_cart');
$this->db->join('tbl_album_image', 'tbl_album_image.id = tbl_cart.photo_id', 'LEFT');
$this->db->where('user_id', $user_id);
return $this->db->get()->result();
}
I'm trying to use php to create a zip file (which it does - taken from this page - http://davidwalsh.name/create-zip-php), however inside the zip file are all of the folder names to the file itself.
Is it possible to just have the file inside the zip minus all the folders?
Here's my code:
function create_zip($files = array(), $destination = '', $overwrite = true) {
if(file_exists($destination) && !$overwrite) { return false; };
$valid_files = array();
if(is_array($files)) {
foreach($files as $file) {
if(file_exists($file)) {
$valid_files[] = $file;
};
};
};
if(count($valid_files)) {
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
};
foreach($valid_files as $file) {
$zip->addFile($file,$file);
};
$zip->close();
return file_exists($destination);
} else {
return false;
};
};
$files_to_zip = array('/media/138/file_01.jpg','/media/138/file_01.jpg','/media/138/file_01.jpg');
$result = create_zip($files_to_zip,'/...full_site_path.../downloads/138/138_files.zip');
The problem here is that $zip->addFile is being passed the same two parameters.
According to the documentation:
bool ZipArchive::addFile ( string $filename [, string $localname ] )
filename
The path to the file to add.
localname
local name inside ZIP archive.
This means that the first parameter is the path to the actual file in the filesystem and the second is the path & filename that the file will have in the archive.
When you supply the second parameter, you'll want to strip the path from it when adding it to the zip archive. For example, on Unix-based systems this would look like:
$new_filename = substr($file,strrpos($file,'/') + 1);
$zip->addFile($file,$new_filename);
I think a better option would be:
$zip->addFile($file,basename($file));
Which simply extracts the filename from the path.
This is just another method that I found that worked for me
$zipname = 'file.zip';
$zip = new ZipArchive();
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
$download_file = file_get_contents($file);
$zip->addFromString(basename($file),$download_file);
$zip->close();
header('Content-disposition: attachment; filename='.$zipname);
header('Content-type: application/zip');
readfile($tmp_file);
I use this to remove root folder from zip
D:\xampp\htdocs\myapp\assets\index.php
wil be in zip:
assets\index.php
our code:
echo $main_path = str_replace("\\", "/", __DIR__ );// get current folder, which call scipt
$zip_file = 'myapp.zip';
if (file_exists($main_path) && is_dir($main_path))
{
$zip = new ZipArchive();
if (file_exists($zip_file)) {
unlink($zip_file); // truncate ZIP
}
if ($zip->open($zip_file, ZIPARCHIVE::CREATE)!==TRUE) {
die("cannot open <$zip_file>\n");
}
$files = 0;
$paths = array($main_path);
while (list(, $path) = each($paths))
{
foreach (glob($path.'/*') as $p)
{
if (is_dir($p)) {
$paths[] = $p;
} else {
// special here: we remove root folder ("D:\xampp\htdocs\myapp\") :D
$new_filename = str_replace($main_path."/" , "", $p);
$zip->addFile($p, $new_filename);
$files++;
echo $p."<br>\n";
}
}
}
echo 'Total files: '.$files;
$zip->close();
}