Download zip folder based on form input - Codeigniter - codeigniter

I want to create search file form, where user search files based on year.I already made folder file in a years (ex. folder 2019, folder 2018, etc), so when user input value the results will show based on user input. I get the result that i want, but i can't download file as zip because the value og path folder is null. I already tried use input-> get and session-> set_flashdata, but the result still null. My question is how do I get the year value, so can direct to the path folder?
Note : tahun is years in english
Controller
public function download_zip() {
// Read files from directory
$tahun = $this->input->get('tahun');
if($this->input-post('but_createzip2') != NULL){
// File name
$filename = $tahun . _laporan.zip;
// Directory path (uploads directory stored in project root)
$path = './uploaded/laporan/'.$tahun.'/';
// Add directory to zip
$this->zip->read_dir($path, FALSE);
// Save the zip file to archivefiles directory
$this->zip->archive('./uploaded/backup_laporan/'. $filename);
// Download
$this->zip->download($filename);
}
// Load view
$this->load->view('v_detail_laporan');
}}
View
<form role="form" action="<?php echo base_url().'laporan'?>">
<input type = "text" id="tahun" name="tahun" class="form-control" placeholder="Masukkan Tahun" required/>
</form>
// Download
<?php echo form_open('laporan/download_zip'); ?>

You are posting dat using GET method then why are you made condition in POST method
public function download_zip() {
// Read files from directory
$tahun = $this->input->get('tahun');
if($this->input->get('tahun') != NULL){ // MODIFIED HERE YOU ARE PASSING VALUES USING GET METHOD
// File name
$filename = $tahun ."_laporan.zip";
// Directory path (uploads directory stored in project root)
$path = './uploaded/laporan/'.$tahun.'/';
// Add directory to zip
$this->zip->read_dir($path, FALSE);
// Save the zip file to archivefiles directory
$this->zip->archive('./uploaded/backup_laporan/'. $filename);
// Download
$this->zip->download($filename);
}
// Load view
$this->load->view('v_detail_laporan');
}
Try this code

You have a wrong form target, try to modify the codes be like below.
View :
<?php echo form_open('laporan/download_zip', ['method' => 'post', 'role' => 'form']); ?>
<?php echo form_hidden('but_createzip2','1');?>
<input type = "text" id="tahun" name="tahun" class="form-control" placeholder="Masukkan Tahun" required/>
<?php echo form_close(); ?>
Controller :
public function download_zip() {
// Read files from directory
$tahun = $this->input->post('tahun');
if($this->input-post('but_createzip2') != NULL){
// File name
$filename = $tahun . _laporan.zip;
// Directory path (uploads directory stored in project root)
$path = './uploaded/laporan/'.$tahun.'/';
// Add directory to zip
$this->zip->read_dir($path, FALSE);
// Save the zip file to archivefiles directory
$this->zip->archive('./uploaded/backup_laporan/'. $filename);
// Download
$this->zip->download($filename);
}
// Load view
$this->load->view('v_detail_laporan');
}

Related

LARAVEL How to transfer file from local (public) to FTP using Laravel

I wanna ask a question, anyone know how to transfer data from local / public to ftp, I'm using Storage class
https://laravel.com/docs/5.4/filesystem
Here's my code
$file_local = Storage::disk('local')->get('public/uploads/ftp/file.pdf');
$file_ftp = Storage::disk('ftp')->put('/file.pdf', $file_local');
But my code is not working, when I open the file on ftp, the file is broken, then I open it with notepad, inside file, the content is 'public/uploads/ftp/file.pdf' the content I mean content should on local not what I was wrote,
Anyone know how to transfer file from local to ftp, sorry for my bad English, Thanks for your answer anyway
To get started, you should know the details of your FTP host, FTP username, and FTP password. Once, you are ready with the details open the .env files and add the details as below:
FTP_HOST=YOUR_FTP_HOST_VALUE
FTP_USERNAME=YOUR_FTP_USERNAME_VALUE
FTP_PASSWORD=YOUR_FTP_PASSWORD_VALUE
Make sure to replace the placeholders with the actual values. Next, open the config/filesystems.php file and add the ‘ftp’ configuration to the ‘disks’ array.
<?php
return [
......
'disks' => [
......
'ftp' => [
'driver' => 'ftp',
'host' => env('FTP_HOST'),
'username' => env('FTP_USERNAME'),
'password' => env('FTP_PASSWORD'),
'root' => 'DIR_PATH_TO_WHERE_IMAGE_STORE' // for example: /var/www/html/dev/images
],
],
];
Replace DIR_PATH_TO_WHERE_IMAGE_STORE with the actual path where you need to store images. For example, if we have folder called ‘images’ and path to this folder is /var/www/html/dev/images then this path will go as the value for ‘root’ in the above array.
For uploading files through FTP we need a form where a user can submit the image. Add the below code in your view file.
<form action="{{ url('PASS_ACTION_URL_HERE') }}" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" name="profile_image" id="exampleInputFile" multiple />
</div>
{{ csrf_field() }}
<button type="submit" class="btn btn-default">Submit</button>
</form>
You should replace the PASS_ACTION_URL_HERE with your actual route. As we are using a Laravel Storage to file uploading user need add Facade to the controller file as follows:
public function store(Request $request)
{
if($request->hasFile('profile_image')) {
//get filename with extension
$filenamewithextension = $request->file('profile_image')->getClientOriginalName();
//get filename without extension
$filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
//get file extension
$extension = $request->file('profile_image')->getClientOriginalExtension();
//filename to store
$filenametostore = $filename.'_'.uniqid().'.'.$extension;
//Upload File to external server
Storage::disk('ftp')->put($filenametostore, fopen($request->file('profile_image'), 'r+'));
//Store $filenametostore in the database
}
return redirect('images')->with('status', "Image uploaded successfully.");
}
‘profile_image’ is the name of our file input. We build the unique name of our file and then uploading it to an external server. Notice we have used Storage::disk(‘ftp’) method. This function would store our file to the path as defined in the configuration. A user should store the value ‘$filenametostore’ in your database.
'local' => [
'driver' => 'local',
'root' => storage_path().'/app',
],
If you use the local disk (config/filesystems.php) you are looking in 'storage/app' not the public folder unless you have changed the default settings. So:
$file_local = Storage::disk('local')->get('file.pdf');
will look for 'Storage/App/file.pdf'
Make sure your pdf is in that folder and give this a try:
$file_local = Storage::disk('local')->get('file.pdf');
$file_ftp = Storage::disk('ftp')->put('file.pdf', $file_local);
EDIT: also, I notice in your original post second line of code you have rogue ' after $file_local ;)

Laravel display image from path which is in database

So use is uploading a logo and it's path is stored in a database like this:
C:\xampp\htdocs\laravel\public\logo\1496912432.jpg
I am displaying the image like this:
<img class="images" id="image" src="{{$business->image}}" />
However I get this error:
Not allowed to load local resource: file:///C:/xampp/htdocs/laravel/public/logo/1496912432.jpg
How can this problem be solved?
//edit
Controller:
public function image(Request $request) {
if($request->hasFile('img'))
{
$image = Input::file('img');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('logo/' . $filename);
Image::make($image->getRealPath())->fit(303, 200)->save($path);
$file = $request->file('img');
$session = session()->get('key');
$update_image = Business::find($session);
$update_image->image = $path;
$update_image->save();
return ['url' => url('logo/' . $filename)];
}
Use Laravel file() to store files https://laravel.com/docs/5.4/requests#files
Store the $path to your db
$path = $request->photo->store('logo');
the $request->photo is depending on your input file attribute name. In your case, it should be $request->img.
the above code will create a folder (if not exist), namely "logo" and store to that folder with random string file name.
Also check your configuration for file, located at /config/filesystem.php. Default is set to public
Use asset function to get the full path from public folder
<img class="images" id="image" src="{{ asset($business->image }}" />
You can do in two ways
Best way is update url path when image saving save url path to db
$path = $request->photo->store('logo'); // in 5.4
The other way if you can't changes db url you can do some hack like this
$file = explode('/public/', $business->image);
echo asset($file[1]);
You want to store all files inside the web root. Because of cross-domain security, you cannot access the file:// domain/protocol from a http protcol. By using Laravel to store and retrieve, it will come from the same host.

Download files by links from .csv file

I have .csv file which has two columns: name and http link:
name,link
IN0895,http://sample.com/images/example.jpg
IN0895,http://sample.com/images/example2.jpg
IN0872,http://sample.com/images/name.jpg
IN0872,http://sample.com/images/screen.jpg
I want create folder with name from first column and download file there (from second column). If folder already exists, just download file and put there.
How this can be done using bash, wget, curl or something else of your choice?
Fields in CSV file are comma separated in your example.
filename for CSV file is given at commandline when you call the script.
modify script permissions.
test it in a temp folder first so you don't clutter and have to clean up if it doesn't work.
not tested
#!/usr/bin/env bash
filename="$1"
while IFS="," read f1 f2
do
mkdir -p "$f1";
wget -P "$f1" "$f2"
done < "$filename"
mkdir -p checks if directory exists and makes directory if it doesn't
wget -P is Prefix (Parent folder) for folder to download to in case you are downloading more than one thing from URL.
f1 and f2 are the 2 fields in CSV file. f1 is the first field which will be the directory name and f2 is the URL.
I wrote something that does this in python. Keep in mind you have to install wget via pip install wget first.
import pandas as pd
import wget
#read in data
data = pd.read_csv("file.csv")
# assuming you have a column named Column1 which contains the link, iterate #through and download
for index, row in data.iterrows():
link = wget.download(row['Column1'])
<?php
// This is the class which is use for cURL operation..
class curl_image {
// Here two variable $name for Rename image, $img_url take image path
function image($name,$img_url)
{
// Here we define a file path where download image will save...
$path = "E:/xampp/htdocs/beauty_code_image/";
// Now initialize curl instance here with related method
$ch = curl_init($img_url);
$fp = fopen($path . $name, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
// cURL excute if above information is right otherwise show error msg
$result = curl_exec($ch);
// print_r($result); it just for display cURL is executed or not
curl_close($ch); // Close cURL here
fclose($fp);
}
}
// Initialize class object here
$obj = new curl_image();
// Here we check file is exist
if(isset($_FILES['file']['name']))
{
// We check here data is in valid mentioned format or not
$csvMimes = array('application/vnd.msexcel','text/plain','text/csv','text/tsv');
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
if(is_uploaded_file($_FILES['file']['tmp_name'])){
//open uploaded csv file with read only mode
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
// fetch csv file here using Php inbuild function
fgetcsv($csvFile);
while(($line = fgetcsv($csvFile)) !== FALSE){
// Here object fetch the method which download image & rename it with SKU name
$obj->image($line[0].'.jpg',$line[1]);
}
}
// Close CSV file
fclose($csvFile);
}
}
?>
<html>
<head></head>
<body>
<div class="panel panel-default">
<div class="panel-body">
<form action="" method="post" enctype="multipart/form-data" id="importFrm">
<input type="file" name="file" />
<input type="submit" class="btn btn-primary" name="importSubmit" value="IMPORT">
</form>
</div>`enter code here`
</div>
</body>
</html>

custom image uploading from frontend in magento code does not work

i've problem in uploading images in my custom module in magento..
i used core php ccoding for this purpose but magento is not uploading image..
i used same code to upload file in my local xampp.
but that code is not working on my server..
i also use this code but it also not working....
$path = Mage::getBaseDir().DS.'customer_documents'.DS; //desitnation directory
$fname = $_FILES['docname']['name']; //file name
$uploader = new Varien_File_Uploader('docname'); //load class
$uploader->setAllowedExtensions(array('doc','pdf','txt','docx')); //Allowed extension for file
$uploader->setAllowCreateFolders(true); //for creating the directory if not exists
$uploader->setAllowRenameFiles(false); //if true, uploaded file's name will be changed, if file with the same name already exists directory.
$uploader->setFilesDispersion(false);
$uploader->save($path,$fname); //save the file on the specified path
I had added this line in my code and it's working..
<?php require_once ("lib/Varien/File/Uploader.php");?>
after this write this code
<?php
$path = Mage::getBaseDir().DS.'customer_documents'.DS; //desitnation directory
$fname = $_FILES['docname']['name']; //file name
$uploader = new Varien_File_Uploader('docname'); //load class
$uploader->setAllowedExtensions(array('doc','pdf','txt','docx')); //Allowed extension for file
$uploader->setAllowCreateFolders(true); //for creating the directory if not exists
$uploader->setAllowRenameFiles(false); //if true, uploaded file's name will be changed, if file with the same name already exists directory.
$uploader->setFilesDispersion(false);
$uploader->save($path,$fname); //save the file on the specified path
?>

File upload in joomla module

I have been searching this for quite a while but couldn't find a solution to match my need. I am developing a module for Joomla 2.5 . I need functionality to allow users to upload images/any file type from the backend in module configuration.
Question : How can I add field for file upload in joomla module.
Thanks!
Just a sample from the joomla docs:
<?php
//Retrieve file details from uploaded file, sent from upload form
$file = JRequest::getVar('file_upload', null, 'files', 'array');
//Import filesystem libraries. Perhaps not necessary, but does not hurt
jimport('joomla.filesystem.file');
//Clean up filename to get rid of strange characters like spaces etc
$filename = JFile::makeSafe($file['name']);
//Set up the source and destination of the file
$src = $file['tmp_name'];
$dest = JPATH_COMPONENT . DS . "uploads" . DS . $filename;
//First check if the file has the right extension, we need jpg only
if ( strtolower(JFile::getExt($filename) ) == 'jpg') {
if ( JFile::upload($src, $dest) ) {
header("Location: http://".$_SERVER["HTTP_HOST"]."/administrator"); Redirect to a page of your choice
} else {
echo "error !"; //Redirect and throw an error message
}
} else {
echo "Wrong extension !"; //Redirect and notify user file is not right extension
}
?>
For more detailed information and full example(s): http://docs.joomla.org/How_to_use_the_filesystem_package
Keep in mind that your HTML form must include
enctype="multipart/form-data"
otherwise you will not get any result with the joomla function!

Resources