Laravel 5.3 photo upload with plupload directory related issue - php

I have recently migrated my code into laravel. I have faced problem with file upload using plupload with laravel. In pluploaded file is uploaded to server before form submitting. After uploaded file succesfully, file path is put in hidden input field.
My Upload Code is given below.
public function photo(){
$target_file = "";
$this->target_dir = base_path() ."/uploads/";
if($_FILES['file']['name']){
$filename = AppUtils::get_new_filename($this->ext);
$filename = "photo_" . $filename;
$target_file = $this->target_dir . $filename;
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$photo = $this->target_dir . $filename;
echo $photo;
die();
}
else{
AppUtils::fail();
}
}
Problem is without using base_path() in $target_dir, file is not uploaded properly. But using base_path() preview image not actual location.
For example, After uploading photo output will be /var/www/htm/lar/uploads/xyz.jpg
But in preview image path shows : http://example.com/lar/var/www/html/lar/uploads/xyz.jpg

Try this:
public function photo(){
$target_file = "";
$this->target_dir = "/uploads/";
if($_FILES['file']['name']){
$filename = AppUtils::get_new_filename($this->ext);
$filename = "photo_" . $filename;
$target_file = base_path() . $this->target_dir . $filename;
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$photo = $this->target_dir . $filename;
echo $photo;
die();
}
else{
AppUtils::fail();
}
}
base_path() should only be used for the upload location.

Related

How to upload Image or large file to temp folder before submit form in laravel

I'm using this code to upload files or images. It's working but can't upload a large file and I want to upload a file when selecting it from the local computer like the below image.
I use below PHP code in the controller.
$image = $request->file('file_upload');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
echo $new_name;
$image->move(public_path('images'), $new_name);
Try to use this code.
Change the $request->sharing_file with your field name.
You can increase the $size for image what you want, currently it is 16mb and working fine.
$myimage = $request->image;
$size = getClientSize();
if($sizes < 16777216){
$fileMimeType = explode('/', $myimage->getClientMimeType());
$fileType = $fileMimeType[0];
$originalFileName = substr($myimage->getClientOriginalName(), 0, strpos($myimage->getClientOriginalName(), "."));
$originalFileName = substr(str_replace(' ', '-', $originalFileName),0,10);
$rand = rand(9,1000);
$fileName = $rand.'-'.$originalFileName.'.'.$myimage->getClientOriginalExtension();
$upload = $values->move(public_path('images'), $fileName);
if($upload) {
$message = 'File Uploaded';
} else {
$message = "Failed to upload file";
}
}
else {
$message = 'Files size should be less than 16 MB.';
}
Try
if ($request->hasFile('file_upload')) {
$destinationPath = public_path().'/images/';
$file = $request->file_upload;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
$input['your_databse_table_field_name'] = $fileName;
}

Laravel can't upload file in storage folder

I used to store my upload files (images) in my public folder but this time I want to store them in my storage folder and I get this error
Can't write image data to path (C:\laragon\www\mynewsite\storage\images/aboutimage-1522481830.png)
Error comes from this line (where I use intervention/image package)
Image::make($image)->resize(1200, 600)->save($location);
My function:
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'aboutimage' . '-' . time() . '.' . $image->getClientOriginalExtension();
$location = storage_path('images/' . $filename);
Image::make($image)->resize(1200, 600)->save($location);
$oldFilename = $indexabout->image;
$indexabout->image = $filename;
Storage::delete($oldFilename);
}
any idea?
UPDATE
My files will upload in root/storage folder instead of root/storage/app/public/images
why is that?
Update 2
I changed my function to code below and it's uploading where it suppose to upload but it does not delete the old image
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = '/aboutimage' . '-' . time() . '.' . $image->getClientOriginalExtension();
$location = storage_path('app/public/images' . $filename);
Image::make($image)->resize(1200, 600)->save($location);
$oldFilename = $indexabout->image;
$indexabout->image = $filename;
Storage::delete($oldFilename);
}
SOLVED
here is final code:
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'aboutimage' . '-' . time() . '.' . $image->getClientOriginalExtension();
$location = storage_path('app/public/images/' . $filename); // root storage path
Image::make($image)->resize(1200, 600)->save($location);
Storage::delete('images/' . $indexabout->image); //public storage path
$indexabout->image = $filename;
}
Basically I gave Root/Storage path to store data and Public/Storage path for deleting them in update method.

Upload image file to server, store name in MySQL DB

I'm trying to create a file upload only my current script doesn't seem to work as I believe it should.
I've managed to get the data saved in the MySQL table okay but I can't seem to get the file into the 'uploads' directory?
if(isset($_POST['new']) && $_POST['new']==1){
$folder = "uploads/";
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);
$trn_date = date("Y-m-d H:i:s");
$brand =$_REQUEST['brand'];
$user =$_SESSION["username"];
$model = $_REQUEST['model'];
$serial =$_REQUEST['serial'];
$purchasedate = $_REQUEST['purchasedate'];
$img1 =$_REQUEST['image1'];
$ins_query="insert into table
(`user`,`trn_date`,`brand`,`model`,`serial`,`purchasedate`,`image1`)values
('$user','$trn_date','$brand','$model','$serial','$purchasedate','$img1')";
mysqli_query($con,$ins_query)
or die(mysql_error());
$status = "added successfully.
</br></br><a href='home.php'>home</a>";
}
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);
What if trying directly what the doc said ;)
$uploads_dir = '/uploads';//try over 'uploads' too or create a 'uploads' folder in you app_root
foreach ($_FILES["image1"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image1"]["tmp_name"][$key];
$name = $_FILES["image1"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Possible Link
I have found an issue in your code.
$folder = "uploads/";
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);
In this case the file does not have the extension
$folder = "uploads/";
$ext = explode('.', basename( $_FILES['image1']['name']));
$upload_image = $folder . basename($_FILES["image1"]["name"].$ext);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);
The uploads folder is in the same directory that is the php script?
You also can verify if the file was correctly moved doing the following test
if (file_exists($upload_image)){
echo "true";
}
Provide a file upload validation before uploading into server it will prevent server from malicious files
How to give file validation in php : Link

Delete image after upload new one

I'm working with laravel 5.4 I have a form which I can upload my logoimage and in update function I have this code:
//Save logo
if ($request->hasFile('logo')) {
$avatar = $request->file('logo');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('avatars/logos/');
$request->file('logo')->move($location, $filename);
$oldFilename = $general_Settings->logo;
$general_Settings->logo = $filename;
Storage::delete($oldFilename);
}
$general_Settings->save();
for updating my image which is work but as you see I have Storage::delete($oldFilename); this part doesn't work and just keep the old image.
what do you think is issue of that?
Solved:
The issue was Filesystem.php I made my local root set to 'root' => public_path('avatars/'), and changed all my functions in my app because no way to save images in sub-folders and delete them just can save in sub-folders.
then my update function become like this:
if ($request->hasFile('logo')) {
$avatar = $request->file('logo');
$filename = 'sitelogo' . '-' . time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('avatars/');
$request->file('logo')->move($location, $filename);
$general_Settings->logo = $filename;
}
$general_Settings->save();
I hope this help someone.
Since, You have stored logo file name only not full path of file,
You need to give full path from public folder to delete image. Change delete line as:
if ($request->hasFile('logo')) {
$avatar = $request->file('logo');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('avatars/logos/');
$request->file('logo')->move($location, $filename);
$oldFilename = $general_Settings->logo;
$file_path = "avatars/logos/".$oldFilename;
$general_Settings->logo = $filename;
Storage::delete($file_path);
}
$general_Settings->save();
This might work.

Uploading image to with custom name in Yii framework

I am trying to upload images from registration form in Yii framework. The image will be saved in "img/avatar" folder and the name of the image should be changed to the username. The piece of code I use for this is below:
//uploading avatar to the img/avatar folder
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$personModel->picture = $upload_file;
$picture_name = $userModel->username;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name);
}
$personModel->save();
//end of image uploading part
The problem is: the name of the username has been saved in picture row of the database. But the image was not uploaded to the folder. I am trying to find out the problem in the code. but cannot solve it. Any suggestions?
Well first thing you need to do is to prevent database input if the picture is not saved.
if(isset($uploadedfile))
{
if($upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name)
{
$personModel->save();
}
else
{
//throw error
}
}
As far as problems in the code go. Most common problem is directories not existing, path to them not being correct.
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$ext = pathinfo($upload_file->picture, PATHINFO_EXTENSION);
$picture_name = $userModel->username . '.' . $ext;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs('/Your_correct_path/.../etc/'.$picture_name);
}
$personModel->save();
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$picture_name = $userModel->username . '.' . pathinfo($upload_file, PATHINFO_EXTENSION);
$personModel->picture = $picture_name;
if (isset($upload_file)) {
$upload_file->saveAs(Yii::app()->basePath . '/../img/avatar/' . $picture_name);
}
$personModel->save();
You have to check your folder permission.
The problem has been solved through following code:
$uploadFile = CUploadedFile::getInstance($personModel, 'picture');
$extension = pathinfo($uploadFile, PATHINFO_EXTENSION);
$fileName = $userModel->username . '.' . $extension;
if (isset($uploadFile)) {
$personModel->picture = $fileName;
$uploadFile->saveAs(Yii::app()->basePath . '/../img/avatar/' . $fileName);
}

Categories