Create table using CSV header in laravel 5.4 - laravel

I want to create a table using CSV file header when I upload a file.
If table does not exists then create table using CSV header
else just import data into a specified table.
This is my file upload code.
if($request->hasFile('file'))
{
$this->validate($request, ['file' => 'mimes:txt,xls,tsv,xlsx' ]);
//Get original file name
$filename = $request->file->getClientOriginalName();
//Get original file extention
$fileExtention = $request->file->getClientOriginalExtension();
//get upload user id
$uploadedUserId = Auth::user()->id;
//get file upload timestamp in microseconds
$microseconds = microtime(true);
//remove special characters from file name
$sansSpecial = preg_replace('/[\'\"\,\(\)\s]/', '_',$filename);
//prepend timestamp to modified file name
$prependTimestamp = $microseconds.'-'.$sansSpecial;
//create unique hash code from modified file name
$uniqueFileHash = Hash::make($prependTimestamp);
$uploadDirectory ='/app/public';
$uploadPath = storage_path().$uploadDirectory;
if(Storage::exists('./public/'.$filename))
{
Use the path info helper function to get file info.
$fileInfo= pathinfo($filename);
//Add timestamp to file if file already exist.
$finsert = $fileInfo['filename'].date('(m-d-y h i s)').'.'.$fileExtention;
//Store file into directory.
$insert = $request->file->storeAs('./public/',$finsert);
//New upload object.
$file = new Upload;
//Assign new file name
$file->file_name = $finsert;
//Assign new modiefied file name with prepended timestamp
$file->modified_file_name = $prependTimestamp;
//Assign unique file hash.
$file->unique_file_hash = $uniqueFileHash;
//Assign full file path
$file->file_full_path = $uploadPath;
//Assign uploaded user id
$file->uploaded_user_id = $uploadedUserId;
//Store all informamation into database.
$file->save();
}

Related

laravel Backpack Original Image Name

I am using laravel backpack for my site and i need to upload some images, i copy the code from their website and works fine, but i need the original name on the images, i tried some things, but is not working.
public function setImageAttribute($value)
{
$attribute_name = "image";
$disk = "uploads";
$destination_path = 'storage/services/' .date('FY').DIRECTORY_SEPARATOR;
if ($value==null) {
Storage::disk($disk)->delete($this->{$attribute_name});
// set null in the database column
$this->attributes[$attribute_name] = null;
}
if (str_starts_with($value, 'data:image'))
{
$file = $value;
$filename = $this->generateFileName($file, $destination_path);
$image = InterventionImage::make($file)->orientate();
$fullPath = $destination_path.$filename.'.'.$file->getClientOriginalExtension();
$this->attributes[$attribute_name] = $fullPath;
}
protected function generateFileName($file, $destination_path)
{
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension());
$filename = Str::random(20);
while (Storage::disk('uploads')->exists($destination_path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = Str::random(20);
}
return $filename;
}
why value alwys take image base64
is there any way to git image original name?
As far as I know, you won't be able to retrieve the filename, as it's always a base64 file. But maybe this work around helps you:
Image fields blade file can be found at:
\vendor\backpack\crud\src\resources\views\crud\fields\image.blade.php
You can overwrite it by making a file on the same name at:
\resources\views\vendor\backpack\crud\fields\image.blade.php
You can change anything there, maybe you can add a hidden input with the file name.

magento 2 read csv from ftp returns a string and not an array

I'm working with Magento 2, I need to read a file through ftp connection. I can login to ftp but I cannot read the csv file. What I did so far (I cut all the unnecessary parts):
use Magento\Framework\File\Csv;
use Magento\Framework\Filesystem\Io\Ftp;
class MyClass {
protected $_csvprocessor;
protected $_ftp;
public function __construct(Csv $csvprocessor, Ftp $ftp) {
$this->_csvprocessor = $csvprocessor;
$this->_ftp = $ftp;
}
public function getCsv() {
$conn = $this->_ftp->open($params); // this works, I can successfully login to ftp
$filecsv = $this->_ftp->read($remotepathtofile); // this gets me the file but it is a string, not an array with the csv data
$this->_csvprocessor->getData($remotepathtofile); // this doesn't work with remote file, only with local path (eg: magentoroot/var/import/file.csv)
}
}
How can I read the csv as an array, as $this->_csvprocessor->getData() would return, but from remote file instead of local?
You need to parse the csv string. Try using the function "fgetcsv". See http://php.net/manual/en/function.fgetcsv.php.
Below the code, you can use to read CSV file an array
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$objectManager1 = Magento\Framework\App\ObjectManager::getInstance();
$directoryList = $objectManager1->get('\Magento\Framework\App\Filesystem\DirectoryList');
$path = $directoryList->getPath('media');
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$myarray = glob("Book1.csv");
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
if(count($myarray)){
/*This will create an array of associative arrays with the first row column headers as the keys.*/
$csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
array_walk($csv_map, function(&$a) use ($csv_map) {
$a = array_combine($csv_map[0], $a);
});
array_shift($csv_map); # remove column header
/*End*/
$message = '';
$count = 1;
foreach($csv_map as $data){
your code....
}
Hope this will help you enjoy...
You can dump the server file to your local.
$filecsv = $this->_ftp->read($remotepathtofile, $destinationFilePath);
where $destinationFilePath is local file path.
Then use that local file.

want to change image in codeigniter

I want to change an image in Codeigniter, replace the previously uploaded image and also delete previous image from folder :
Here is my Controller . But its not working:
public function changeImage(){
//$user_id = $this->profile_model->changeImage();
/************* File Upload ************/
$config['upload_path'] = './uploads/user_pic/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload',$config);
$filetype = $_FILES['user_pic']['type'];
$file_name = $_FILES['user_pic']['name'];
if($filetype == "image/jpg")
$file_type='jpg';
else if ($filetype == "image/gif")
$file_type='gif';
else if($filetype == "image/jpeg")
$file_type='jpg';
else if($filetype == "image/pjpeg")
$file_type='pjpeg';
else if($filetype == "image/png")
$file_type='png';
$_FILES['user_pic']['name']=$user_id.'.'.$file_type;
$this->upload->do_upload('user_pic');
$up_dtat = array('user_pic' => $_FILES['user_pic']['name']);
$this->db->where('user_id',$user_id);
$this->db->update('tbl_users',$up_dtat);
redirect('profile');
}
if you need to update the profile picture in your store file, first you need to remove the old file, fetch the old file name on the bases of user id.
Then give the file name with this code.
unlink("your_path/filename.jpg"); //don't use base_url() just give the path like profile_pic/xxxxx.png
This code will delete the specified file from that folder.
Now i have code that i had use for the file uploads so it will also work for you try this.
$imgpath='uploads/profile_pic/';//path where do you want to store image
$all_img="";
if($_FILES["profile_pic"]['name'])//input type that you have use in file upload
{
$path_parts = pathinfo($_FILES["profile_pic"]["name"]);
$image_path = $path_parts['filename'].'_'.time().'.'.$path_parts['extension'];
$all_img.=$image_path;
move_uploaded_file($file_tmp=$_FILES["profile_pic"]["tmp_name"],$imgpath."/".$image_path);
$data['cm_user_profile_pic']=$all_img;//store filename in array to update in database
}
If you want to replace the previous image only but set file name same then
First method is :
get old file name from table
$sql = "SELECT user_pic FROM tbl_users WHERE user_id=?";
$get_image = $this->db->query($sql,array($user_id))->row_array();
set new file name as assigned to old
$config['file_name'] = $get_image['user_pic'];
$config['overwrite'] = TRUE; // this will overwrite your image
$this->load->library('upload', $config);
But in this case, old file and new file extension must be same
If both extensions are different then maybe image will be crashed after upload
The second method is
Get user_pic data from DB
And Unlink that picture
unlink($_SERVER['DOCUMENT_ROOT'].'/'.Your_image_folder.$get_image['user_pic']);
And check file is upload or not
if ( ! $this->upload->do_upload('user_pic')) {
$error = array('error' => $this->upload->display_errors());
}
else {
$data = array('upload_data' => $this->upload->data());
}

Laravel returns uploaded file instead of it path

I am uploading a file and saving it in local storage. These files are stored in the database related to a particular user. When i return the last saved user. I get other details in response properly. But instead of the file path. I get the file as response
$file = $request->file('resume');
$profile_id = $request['profile_id'];
$original_name = $_FILES['resume']['name'];
$resume_new_name = str_random(). '.' . $file->getClientOriginalExtension();
$new_file = $request->file('resume')->move('resources/assets/resumes',$resume_new_name);
$candidate_info['resume'] = $new_file;
$candidate = new candidate();
if (empty($candidate_info['name'])) {
$candidate_info['name'] = $candidate_info['email'];
}
$candidate->name = $candidate_info['name'];
$candidate->phone = $candidate_info['phone'];
$candidate->email = $candidate_info['email'];
$candidate->resume = $candidate_info['resume'];
$candidate->client_id = \Auth::user()->id;
$candidate->status = "new";
$candidate->profile_id = $profile_id;
$candidate->save();
return response()->json(['msg' => $candidate]);
In database column 'resume' it stores the path. But in json response it sends the whole file instead of the path. how do i send the path instead of sending the whole file
Just return the value of that one column:
return response()->json(['msg' => $candidate->resume]);
Instead of using move use store
$new_file = $request->file('resume')->store('resources/assets/resumes',$resume_new_name);

How I can get the file id after upload a file to google drive?

I want to know the file id after upload. find it from file list, I think that isn't good idea and performance. so, How I can get the file id with good idea?
Thanks!
For example:
$file = new Google_Service_Drive_DriveFile();
$file->setName($fileTitle);
$result = $service->files->create(
$file,
array(
'data' => file_get_contents(FILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
)
);
Var $result contain all information about uploaded file,so all you have to do is to display or use id.
echo 'Uploaded file id is '.$result['id'];
For someone coming from .Net background, use:
string fileId = request.ResponseBody.Id;
To get download link also, remember to set
request. Fields = "id, webContentLink";
string fileId = request.ResponseBody.Id;
string downloadLink = request.ResponseBody.WebContentLink;
In order to get download link you will need to set shared permission to the uploaded file after uploading the file.
var permission = new Permission { AllowFileDiscovery = true, Type = "anyone", Role = "reader" };
await driveService.Permissions.Create(permission, request.ResponseBody.Id).ExecuteAsync();

Resources