public function folderdownload(){
try{
$this->load->library('zip');
$this->load->helper('file');
$where = array(
'file_perm_id'=>$this->input->post('id'));
$this->load->model('fetch_model');
$file_path = $this->fetch_model->getalldata($this->folderpath,$this->master,$where);
$path = ##$file_path[0]->folder_path ;
$files = get_filenames($path);
// when i used print_r($files); to verify that i can see the files i can see it from here
foreach($files as $f){
if (is_file($path . $f))
$this->zip->add_data($f, file_get_contents($path . $f));
}
ob_end_clean();
$this->zip->download(date('m-d-Y'));
}catch(Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
I have this controller that once the use click the download button it download all the files within the folder but when I open it it says that the archieve is either unknown format or damaged. please help hoiw can I download files and zip it this is in codeigniter. thanks anyone
public function folderdownload(){
try{
$this->load->library('zip');
$this->load->helper('file');
$where = array(
'file_perm_id'=>$this->input->get('id'));
$this->load->model('fetch_model');
$file_path = $this->fetch_model->getalldata($this->folderpath,$this->master,$where);
$path =$file_path[0]->folder_path ;
$finallink = ($_SERVER['DOCUMENT_ROOT'] . "/cobacfms/" . $path);
$this->zip->read_dir(($finallink), false);
$this->zip->download(date('m-d-Y'));
}catch(Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
This is the solution to my problem
Your zip file creation is having issue.
I would suggest you to first check you content availability and then create zip file and at last download it.
To create ZIP file
$sourcePath = 'uploads/sourceDirectory';
$targetPath = 'uploads/destDirectory';
if (file_exists($sourcePath)){
if(!copy($sourcePath, $targetPath)){ //Copy file source to destination directory
return ['status' => false, 'msg' => 'File missing'];
}
}
if (file_exists($targetPath)){ // check target directory
$this->zip->read_dir($targetPath,False); // read target directory
if(!$this->zip->archive($targetPath.'.zip')){ // zip target directory
return ['status' => false, 'msg' => 'Zip file creation Failed!'];
}else{
return ['status' => false, 'msg' => 'Zip file Created'];
}
}
Related
I am using PHP to download a number of files as zip folder, see code below,
it shows me this error zipArchive::close() Read error: no such file or directory in C:// path
I have added HTML button on click to take the id of the row to download its files
if (isset($_GET['zip'])) {
$zip_id = $_GET['zip'];
$query4 = "select f.id f.file_name, f.path, r.user_id from register r "
. "join files f on f.register_id =r.user_id "
. "where r.user_id=$zip_id";
$result4 = mysqli_query($con, $query4);
if (($result4)) {
while ($row = mysqli_fetch_array($result4)) {
$document[$row['id']] = array(
'id' => $row['id'],
'file_name' => $row['file_name'],
'path' => $row['path']
);
}
}
// folder to load files
if (extension_loaded('zip')) {
// Checking ZIP extension is available
foreach($document as $f){
$files[]='uploads/'.$f['path'];
}
if ($files != null) {
// Checking files are selected
$zip = new ZipArchive(); // Load zip library
$zip_name = 'folder.zip'; // Zip name
if ($zip->open($zip_name, ZIPARCHIVE::CREATE) !== TRUE) {
// Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time";
}
foreach ($files as $file){
$zip->addFile($file,$file);} // Adding files into zip
$zip->close();
if (file_exists($zip_name)) {
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . $zip_name . '"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}
} else {
$error .= "* no file to zip ";
}
} else {
$error .= "* You dont have ZIP extension";
}
}
I found the error in my code. I have declared & initialized the $document array inside the while loop which is not defined for the zipArchive(). So, it cannot see it then it returns null.
the correction I have defined the creation of the $files inside the while loop.
I am able to upload jpg and pdf to my server (database). Now, I want to be able to download it when I click on the file itself in my view as shown below.
When I click on the file, it routes me to the download page and says page cannot be found and the file is not downloaded
What am I not doing right?
Controller
public function upload(Request $request)
{
$storeFiles = new File;
$uniqueFileName = uniqid() . Input::file('upload_file')->getClientOriginalName() . '.' . Input::file('upload_file')->getClientOriginalExtension();
Input::file('upload_file')->move(public_path('/public/files') . $uniqueFileName);
$storeFiles->path = $uniqueFileName;
$storeFiles->description = Input::get('description');
$storeFiles->save();
return redirect()->back()->with('status', 'File uploaded successfully.');
}
public function download($filename)
{
$file_path = public_path('/public/files'). $filename;
if (file_exists($file_path))
{
// Send Download
return Response::download($file_path, $filename, [
'Content-Length: '. filesize($file_path)
]);
}
else
{
// Error
exit('Requested file does not exist on our server!');
}
}
Routes
Route::get('/course/download/{{file?}}', 'FileController#download')->name('course.download');
View
<td>{{$file->path}}</td>
I am trying to zip some images as user-selected.up to now I have come up with a solution for zipping.My problem is after I zip the relevant data to zip file how can I download it through the browser.i have tried different methods still not working.when I create zip it stored in the public folder.how can I download the zip file from there through the browser?
Here is my code
$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!');
}
In response i'm getting something like this:
The problem is you're trying to load the file via AJAX, which you can't do the way that you're trying to do it.
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'];
}
Change your javascript to:
let xhr = new XMLHttpRequest(), self = this;
window.location = window.location.origin+'/download-file/' + this.selected
Hope this helps you!
Try changing
return Response::download($fileurl, 'Photos.zip', ['Content-Length: '. filesize($fileurl)]);
to
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)));
try this way may be it help. just return you zip file and path name in ajax success
in controller
$fileurl = public_path()."/Photos.zip";
if (file_exists($fileurl))
{
return response()->json($fileurl);
}
else
{
exit('Requested file does not exist on our server!');
}
then add this line
success: function (data) {
'download': data.fileurl,
}
I can upload .docx file to google drive from my apps, but when i tried to upload .doc file, this error appeared :
An error occurred: Error calling POST https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&key=AIzaSyCm1WqPp05lBRjKSpxdtHjS8lz6WLeoWlU: (400) Invalid mime type provided
That error appeared too when I uploaded .ppt .xls file. The documentation says we can store any MIME type in Google Drive. What's wrong here? Anybody knows?
This is my upload function :
function insertFile($title, $description, $parentId, $mimeType, $filename) {
$file = new DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
if ($parentId != null) {
$parent = new ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $this->service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
[UPDATE] I'm using CI and this is my function in controller that calls insertFile function :
function upload() {
$title = $this->input->post('title');
$description = $this->input->post('description');
$parentId = $this->input->post('parentId');
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
$driveHandler = new DriveHandler($_SESSION['credentials']);
$driveHandler->BuildService($_SESSION['credentials']);
$ext = substr(strrchr($_FILES["file"]["name"],'.'),1);
if($title === ""){
$fileTitle = $_FILES["file"]["name"];
} else {
$fileTitle = "$title.$ext";
}
$driveHandler->insertFile($fileTitle, $description, $parentId, $_FILES["file"]["type"], $_FILES["file"]["tmp_name"]);
}
When I try to use var_dump($mimeType) for .docx file, the result is :
string(71) "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
and for .doc file :
string(20) ""application/msword""
Based on the results, I found the problem. There is an additional double quote in $mimeType for .doc file. So I try to change my code like this :
$data = file_get_contents($filename);
$mime = str_replace('"', "", $mimeType);
$createdFile = $this->service->files->insert($file, array(
'data' => $data,
'mimeType' => $mime,
));
It now works.
Rather than just replacing double quotes, you can use a negative character class in regular expression with preg_replace() to replace any non alphanumeric, /, or . characters.
$mimeType = preg_replace("~[^a-zA-Z0-9/\.]*~", "", $mimeType);
I am trying to upload a zipped file using codeigniter framework with following code
function do_upload()
{
$name=time();
$config['upload_path'] = './uploadedModules/';
$config['allowed_types'] = 'zip|rar';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->library('unzip');
// Optional: Only take out these files, anything else is ignored
$this->unzip->allow(array('css', 'js', 'png', 'gif', 'jpeg', 'jpg', 'tpl', 'html', 'swf'));
$this->unzip->extract('./uploadedModules/'.$data['upload_data']['file_name'], './application/modules/');
$pieces = explode(".", $data['upload_data']['file_name']);
$title=$pieces[0];
$status=1;
$core=0;
$this->addons_model->insertNewModule($title,$status,$core);
}
}
But the main problem is that when extract function is called, it extract the zip but the result is empty folder. Is there any way to overcome this problem?
$zip = new ZipArchive;
$res = $zip->open($fileName);
if($res==TRUE)
{
$zip->extractTo($path.$fileName);
echo "<pre>";
print_r($zip);//to get the file type
$zip->close();
try this :
<?php
exec('unzip filename.zip');
?>
Hmm.., I think you set an incorrect path of your uploaded zip file OR your destination path ('./application/modules/') is incorrect.
Try this :
$this->unzip->extract($data['upload_data']['full_path'], './application/modules/');
I use this -> $data['upload_data']['full_path'], to make sure that it's a real path of the uploaded file.
Hope it helps :)
same problem i faced few min back.if you observe carefully you find
please copy zip file and paste to folder contain programe file(.php) after that you
i think file is not store in temp folder.
if(preg_match("/.(zip)$/i", $fileName))
{
$moveResult= move_uploaded_file($fileTmpLoc, $fileName);
if($moveResult == true)
{
$zip = new ZipArchive;
$res = $zip->open($fileName);
if($res==TRUE)
{
$zip->extractTo($path.$fileName);
echo "<pre>";
print_r($zip);
$zip->close();
} else {
echo 'failed';
}
}
unlink($fileName); // Remove the uploaded file from the PHP temp folder
//exit();
}`
class Upload extends CI_Controller {
function __construct(){
parent::__construct();
// load ci's Form and Url Helpers
$this->load->helper(array('form', 'url'));
}
function index(){
$this->load->view('upload_form_view', array('error' => ' ' ));
}
function file_upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'zip';
$config['max_size'] = '';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form_view', $error);
}else{
$data = array('upload_data' => $this->upload->data());
$zip = new ZipArchive;
$file = $data['upload_data']['full_path'];
chmod($file,0777);
if ($zip->open($file) === TRUE) {
$zip->extractTo('./uploads/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
$this->load->view('upload_success_view', $data);
}
}
}
In case anyone comes here for same question, just add chmod($file,0777); to the original code posted yetAnotherSE. That solves the issue of empty files.