Change directory for uploading image - laravel

How can I change the directory of the uploaded images.
I want to upload it in the App/public/files folder.
My code here:
public function update(Request $request, Organigramme $organigramme)
{
$id = $organigramme->id;
$organigramme = Organigramme::find($id);
$organigramme->matricule = $request->input('matricule');
if ($request->has('profile_image'))
{
$image = $request->file('profile_image');
$name = str_slug($request->input('matricule'));
$folder = '/uploads/images/';
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
$this->uploadOne($image, $folder, 'public', $name);
$organigramme->profile_image = $filePath;
$organigramme->save();
}
return view( 'admin.organigrammes.show', compact('organigramme'));
}
public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null)
{
$name = !is_null($filename) ? $filename : str_random(25);
$file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $disk);
return $file;
}

In the config/filesystems file add a new save path.For example:
'images' => [
'driver' => 'local',
'root' => base_path().'/app/public/files',
],
In the code itself, use the following code to save:
Storage::disk('images')->put($path, $image);

Related

Sending an image with HTTP POST

Recently I wanted to separate my project in different services to I wanted to make blogs independent from the project.
In the first project i have written this code. I want to send the data that i get from the form to another API http://127.0.0.1:100/api/saveBlog
public function update(Request $request, $blog)
{
if (!$blog instanceof Blog) {
$blog = $this->getById($blog);
}
$response = Http::post("http://127.0.0.1:100/api/saveBlog",[
'name' => $request->input('name'),
'description' => $request->input('description'),
'name' => $request->input('name'),
'photto' => $request->file('photto')
]);
dd($response->status());
}
In the API service i am trying to read the data
Route::post("/saveBlog",function (Request $request){
$blog = new Blog();
$blog->name = $request->input('name');
$blog->description = $request->input('description');
$blog->name = $request->input('name');
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
return $blog->save();
});
But i am getting 500 status error and blog is not being saved in database.
I think the problem is with $request->file('photto')
ANY IDEA?
check whether image exist in request like below
if($request->has('photto')){
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
}
Updates
$photo = fopen(public_path('/storage/filename'), 'r');
$response = Http::
attach('photo', $photo)
->post($url, [
'param_1' => 'param_1 contents',
...
]);

Laravel file upload s3 Multipart

how do I integrate the multipart upload of s3? I am uploading to s3 and everything works. just I want to refactor the code to S3 multipart upload because the files are too large on the server
// Amazon checking folder
$directory = 'Case/'. $caseDir;
foreach ($request->file('fileslab') as $s3file) {
// Getting request names & extension
$s3patientFirstName = $request->patient_firstname;
$s3patientLastName = $request->patient_lastname;
$s3SavedOrigName = $s3file->getClientOriginalName();
$SendFileToS3 = $s3patientFirstName . '_' . $s3patientLastName . '_' . time() . $s3SavedOrigName;
$contents = file_get_contents($dbfile->getRealPath());
$path = Storage::disk('s3')->put($directory. '/' .$SendFileToS3, $contents);
if (!Storage::disk('s3')->exists($directory)){
Storage::disk('s3')->makeDirectory($directory);
$path = Storage::disk('s3')->put( $directory. '/' . $SendFileToS3, $contents );
}else{
$path = Storage::disk('s3')->put( $directory. '/' .$SendFileToS3, $contents);
}
The Amazon SK Example is below:
require 'vendor/autoload.php';
use Aws\Common\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;
$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
// Prepare the upload parameters.
$uploader = new MultipartUploader($s3, '/path/to/large/file.zip', [
'bucket' => $bucket,
'key' => $keyname
]);
// Perform the upload.
try {
$result = $uploader->upload();
echo "Upload complete: {$result['ObjectURL']}" . PHP_EOL;
} catch (MultipartUploadException $e) {
echo $e->getMessage() . PHP_EOL;
}
I fixed it.
foreach ($request->file('fileslab') as $s3file) {
$directory = 'Case/'. $caseDir;
$contents = fopen($s3file, 'rb');
$s3patientFirstName = $request->patient_firstname;
$s3patientLastName = $request->patient_lastname;
$s3SavedOrigName = $s3file->getClientOriginalName();
$SendFileToS3 = $s3patientFirstName . '_' . $s3patientLastName .
'_' . time() . $s3SavedOrigName;
$disk = Storage::disk('s3');
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-west-1'
]);
$uploader = new MultipartUploader($s3, $contents, [
'bucket' => $_ENV['AWS_BUCKET'],
'key' => $SendFileToS3,
]);
try {
$result = $uploader->upload();
} catch (MultipartUploadException $e) {
return $e->getMessage();
}
}
```

How to delete old picture after new one uploaded

I have this in my Controller which handles image upload
public function updateProfileImage(Request $request)
{
$user = auth('api')->user();
$image = $request->input('image'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'profile' . time() . '.' . $image_extension[1];
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
}
How can i delete the old picture from the directory after new one has been uploaded.
You can delete the image with Storage::delete() method (https://laravel.com/docs/7.x/filesystem#deleting-files). So, get the image before you update, then delete when it's ok to do:
$oldImage = $user->profilePicture;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
Storage::disk('public')->delete($oldImage);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
PS: I'm not sure if the profilePicture attribute is the same of your storage. Anyway, make any adjustment to match if needed.

updated image stores in database but not folder in laravel

problem is that company_photo stores in database but not store in company_photos folder, please tell me where i going wrong..
public function update(Request $request, Company $company,CompanyOtherInfo $CompanyOtherInfo )
{
//dd($company);
//dd(request()->all());
if($request->hasFile('company_photo')){
$files=public_path().'/company_photos/'.$req->input('company_photo1');
File::delete($files);
//dd($files);
$file = $req->file('company_photo');
$destinationPath = public_path().'/company_photos/';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
// echo $filename;
}
else{
$filename=$request->input('company_photo1');
}
//dd($request);
//dd($filename);
$company::where('companies.company_id',$company->company_id)
->update([
'company_photo' => $filename,
'company_name' => request('company_name'),
'company_email' => request('company_email'),
'company_mobile' => request('company_mobile'),
'company_country' => request('company_country'),
'company_state' => request('company_state'),
'company_city' => request('company_city'),
'company_pincode' => request('company_pincode'),
'company_address' => request('company_address'),
'industry_id' => request('industry_id'),
'segment_id' => request('segment_id'),
'company_code' => request('company_code'),
'contact_person'=>request('contact_person'),
]);
The issue you had is you changed the variable $request to $req half way through your code:
Change these lines:
$files = public_path().'/company_photos/'.$req->input('company_photo1');
$file = $req->file('company_photo');
to:
$files = public_path().'/company_photos/'.$request->input('company_photo1');
$file = $request->file('company_photo');
Here is the code with a little refactor:
$filename = $request->input('company_photo1');
if ($request->hasFile('company_photo')) {
$files = public_path().'/company_photos/'.$fileName;
File::delete($files);
$file = $request->file('company_photo');
$file->move(public_path().'/company_photos/', $file->getClientOriginalName());
}

Upload multiple images from different input type files in laravel

I have 4 input type file with different name.How can i upload 4 images into the public folder and into 4 different column in database in same time?
$files=[];
if($request->hasfile('image_front_before')) $files[] = $request->file('image_front_before');
if($request->hasfile('image_back_before'))$files[] = $request->file('image_back_before');
if($request->hasfile('image_left_before'))$files[] = $request->file('image_left_before');
if($request->hasfile('image_right_before'))$files[] = $request->file('image_right_before');
if i dd(files); it will show below..It will appear the images that i have upload
array:4 [▼
0 => UploadedFile {#441 ▶}
1 => UploadedFile {#445 ▶}
2 => UploadedFile {#439 ▶}
3 => UploadedFile {#442 ▶}
]
I think the problem is here..
foreach ($files as $file)
{
if(!empty($file))
{
$filename= md5(time()).'.'.$file->getClientOriginalExtension();
$path = app(GlobalBookingController::class)- >getBookingImageDirectory();
$location = public_path($path.$filename);
Image::make($file)->save($location);
$data[]=$filename;
}
}
Below is the code to insert images into database
$vehicle_image =BookingVehicleImage::updateOrCreate(
[
'booking_id' => $id
],
[
'image_front_before' =>$data[0],
'image_back_before' =>$data[1],
'image_left_before' =>$data[2],
'image_right_before' =>$data[3]
]
);
if i upload 4 images in the same time only 2 will be upload into into public folder ..Sometimes for column image_left_before and image_right_before the images is correct..but for the column image_front_before will contain image_left_before and image_back_before will contain image_right_before..Sometimes only one column has right images and the other column has 3 same images even upload the different images at the start.
Try this example
public function store(Request $request)
{
$this->validate($request, [
'image1' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image2' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image3' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image4' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$article = new Article();
if ($request->hasFile('image1')) {
$image = $request->file('image1');
$name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/articles');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$article->image1 = $name;
}
if ($request->hasFile('image2')) {
$image = $request->file('image1');
$name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/articles');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$article->image2 = $name;
}
if ($request->hasFile('image3')) {
$image = $request->file('image3');
$name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/articles');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$article->image3 = $name;
}
if ($request->hasFile('image4')) {
$image = $request->file('image');
$name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/articles');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$article->image4 = $name;
}
$article->title = $request->get('title');
$article->category_id = $request->get('category_id');
// $article->image = str_slug($request->get('image'));
$article->subtitle = $request->get('subtitle');
$article->description = $request->get('description');
$article->save();
return back()->with('success', 'Your article has been added successfully. Please wait for the admin to approve.');
}
This code is for saving multiple images to the particular path and to database
$i = 0;
foreach ($files as $file)
{
if(!empty($file))
{
$fileName = time().$i++.'.'.$file->getClientOriginalExtension();
Image::make($file)->save(public_path('/img/'.$fileName)); //This line will save your image to the particular path
array_push($files,$fileName);
$obj->image = $fileName;
$obj->save(); //save data to database
}
}

Resources