How to show response path when update image in laravel rest api? - php

I'm trying to build a REST API with Laravel where users need to update their images. In this case the image has been successfully saved in storage, but I want a response in the form of a link that can be accessed by the frontend later. However, the response was not found. Is there a solution to this problem? Here I attach my code
public function update(Request $request,$userId)
{
$user= User::find($userId->id);
// $photoWithExt= $request->file('photo')->getClientOriginalName();
$filename = $user['nip'];
$extension = $request->file('photo')->getClientOriginalExtension();
$fileNameToStore ='/images/users/'.$filename.'.'.$extension;
$path= $request->file('photo')->storeAs('',$fileNameToStore);
$user->update([
'username'=>$request['username'],
'name'=>$request['name'],
'photo'=> $path
]);
return $user;
}
This is response in postman
And when I click the link path, the image is 404. I hope someone can help with this problem

Assuming that you're using Local Drive, you have to get the absolute link to the file
(...)
$user->update([
'username'=>$request['username'],
'name'=>$request['name'],
'photo'=> Storage::disk('local')->get($path); // <---
]);
return $user;
}

I have found the answer,
public function update(Request $request,$userId)
{
$user= User::find($userId->id);
$filename = $user['nip'];
$extension = $request->file('photo')->getClientOriginalExtension();
$fileNameToStore ='images/users/'.$filename.'.'.$extension;
$path= $request->file('photo')->storeAs('',$fileNameToStore,'public');
$photoURL = Storage::url($path); //base_url
$user->update([
'username'=>$request['username'],
'name'=>$request['name'],
'photo'=> $photoURL,
]);
return $user;
}

Related

Request $request convert to Array $data

I'm new at laravel and i was reading the document for a week now. i was working on crud about modification of register form i'm almost finish but then i bump in to this problem which is now i'm trying to look for a right syntax on my question would be how to i check and move a file use as a parameter to store and create a path folder for the image. similar to the code below i show using Request. cause if you look at the register page controller at the create function the parameter used is array.
tried reading documents and research couldn't find any or maybe i lack of keywords to direct me into this type of problem.
I have this code and this is right
public function store(Request $Request)
{
$ProfileUser = new User();
if($Request->hasfile('Img1'))
{
$file = $Request->file('Img1');
$extension = $file->getClientOriginalExtension(); // Get Image Ext.
$filename = time() . "." . $extension;
$file->move('uploads/employee/', $filename);
$ProfileUser->image1 = $filename;
} else
{
return $Request;
$ProfileUser->image1 = 'no image';
}
$ProfileUser->fname = $Request->input('fname');
$ProfileUser->mname = $Request->input('mname');
$ProfileUser->lname = $Request->input('lname');
$ProfileUser->homeaddress = $Request->input('homeaddr');
$ProfileUser->mobilenum = $Request->input('mobilenum');
$ProfileUser->accounttype = $Request->input('typeAcc');
$ProfileUser->image1 = $Request->input('img1');
$ProfileUser->save();
return redirect()->route('home');
}
but then i also have this modification in make:auth i made and added columns
this is my problem here since the function is using an array instead of the Request.
protected function create(array $data) <-- this is the Error
{
if($data->hasFile('image1')) { <-- from here to:
$file = $data->file('image1');
$extension = $file->getClientOriginalExtension(); // Get Image Ext.
$filename = time() . "." . $extension;
$file->move('uploads/employee/', $filename);
} else {
return $request;
} <-- here this function
$user = User::create([
'name' => $data['fname'] . " " . $data['lname'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'fname' => $data['fname'],
'mname' => $data['mname'],
'lname' => $data['lname'],
'homeaddress' => $data['homeaddr'],
'mobilenum' => $data['mobilenum'],
'accounttype' => $data['typeAcc'],
'image1' => $data['image1']
]);
return $user;
}
if i commend out the file validation the create function work fine and is able to save to database but then i need the image to be move on the 1st function it works perfect but in the 2nd using a parameter array doesn't i know i have maybe a wrong syntax which i ask for now how. and if it's ok can you guys explain a bit about the difference between Request vs Array? that i may able also to understand both
The $Request variable contains an object from the Laravel Request class (Illuminate \ Http \ Request). Read more about here
An Array is a PHP data structure. Read about arrays in PHP here.
To get all request's data as an array, you can call the method all() on the request object. It will give you an associative array.
$request->all();

Laravel: can't get post data using Postman form-data

Currently I'm developing a RESTful API so I created a method to upload images but can't the post data using Postman form-data
Here's the screenshot of the request on the Postman.
I've tried to print the request but still can't get the data.
Upload image code
public function fileUpload(Request $request, $id)
{
//print_r($request->file('photo'));
//exit;
$rules = [
'photo' => 'image|mimes:jpeg,jpg,png|max:2048'
];
$this->validate($request, $rules);
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$filename = time().'.'.$file->getClientOriginalExtension();
$request->file('photo')->move(public_path('storage/images'), $filename);
}
return response()->json(['message' => 'Image successfully uploaded'], 200);
}
I want to get post data(photo) through laravel request.

PHP upload file with api

I am developing an api endpoint to use with my laravel and vue app.
public function avatar(Request $request)
{
$user = User::find(Auth::id());
$validator = Validator::make($request->all(), [
'avatar' => 'required'
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
} else {
$image = $request->get('avatar');
//base64_decode($file_data)
$path = Storage::putFile('avatars', base64_decode($image));
$user->avatar_url = $path;
if ($user->save()) {
//return redirect()->route('user_profile_settings');
}
}
}
This is the code that I have I tried going off what I found online to accomplish file uploads with an api and using php, but I am getting this error "Call to a member function hashName() on string". The goal of this is to upload the file to a s3 bucket using the putFile method.
I believe your problem lies here:
$image = $request->get('avatar');
$path = Storage::putFile('avatars', base64_decode($image));
Per the docs, you're going to want to use $request->file('avatar') to access the file.
Then, you can do store('avatars') to store it in your default storage location.
In short:
$path = $request->file('avatar')->store('avatars');

Add watermarks to multiple images using Dropzone.js and Laravel 5.5

I have a form where a user can upload multiple images with Dropzone.js and then I store those images in the database and in the public/images folder.
But what I need is to add a watermark to all of these images before I save them in the public/images directory, because these images will show in the front-end as "preview" images.
I found documentation on how to add watermarks using Intervention Image here.
But I just cant figure out how I would proceed in adding that in my current setup.
Here is my form with the script:
<div id="file-preview_images" class="dropzone"></div>
<script>
let dropPreview = new Dropzone('#file-preview_images', {
url: '{{ route('upload.preview.store', $file) }}',
headers: {
'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content
}
});
dropPreview.on('success', function(file, response) {
file.id = response.id;
});
</script>
$file variable is when a user clicks on create a new File, it creates a new File with a unique identifier before its even saved. A file can have many uploads.
Here is my store method:
public function store(File $file, Request $request) {
// Make sure the user owns the file before we store it in database.
$this->authorize('touch', $file);
// Get the file(s)
$uploadedFile = $request->file('file');
$upload = $this->storeUpload($file, $uploadedFile);
$request->file( 'file' )->move(
base_path() . '/public/images/previews/', $upload->filename
);
return response()->json([
'id' => $upload->id
]);
}
protected function storeUpload(File $file, UploadedFile $uploadedFile) {
// Make a new Upload model
$upload = new Upload;
// Fill the fields in the uploads table
$upload->fill([
'filename' => $uploadedFile->getClientOriginalName(),
'size' => $uploadedFile->getSize(),
'preview' => 1
]);
// Associate this upload with a file.
$upload->file()->associate($file);
// Associate this upload with a user
$upload->user()->associate(auth()->user());
// Save the file
$upload->save();
return $upload;
}
All of that works as intended, I just need to add watermarks to each of these images, which I'm having trouble with.
I already saved a watermark image in public/images/shutterstock.png
I figured it out. This is what I had to do:
public function store(File $file, Request $request) {
// Make sure the user owns the file before we store it in database.
$this->authorize('touch', $file);
// Get the file(s)
$uploadedFile = $request->file('file');
$upload = $this->storeUpload($file, $uploadedFile);
// Get the image, and make it using Image Intervention
$img = Image::make($request->file('file'));
// Insert the image above with the watermarked image, and center the watermark
$img->insert('images/home/shutterstock.png', 'center');
// Save the image in the 'public/images/previews' directory
$img->save(base_path() . '/public/images/gallery/pre/'.$upload->filename);
return response()->json([
'id' => $upload->id
]);
}
And on the "storeUpload" method, changed the 'filename' too:
$upload->fill([
'filename' => $file->identifier.'-'.uniqid(10).$uploadedFile->getClientOriginalName(),
'size' => $uploadedFile->getSize(),
'preview' => 1
]);

How to download a file from URL without showing the full path in laravel?

Download link:-
<a href='"+ downloadlink + '/attachment-download/' + $('#employee_ID').val()+'/'+ res[i].file_name +"'>
Route:-
Route::get('/attachment-download/{id}/{filename}', array(
'uses' => 'AttachmentsController#getDownloadAttachments'
));
Attachment Controller:-
public function getDownloadAttachments($id,$filename){
$file="./img/user-icon.png";
$resource = \Employee::WhereCompany()->findOrfail($id);
$path = $this->attachmentsList($resource);
foreach($path as $index => $attachment){
if ($filename == $attachment['file_name']) {
$filePath = $attachment['url'];
}
}
//return \Response::download($file);
return \Response::download($filePath);
}
File URL Output:-
https://zetpayroll.s3.ap-south-1.amazonaws.com/employees/81/Screenshot%20from%202017-04-26%2015%3A07%3A45.png?X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAI57OFN3HPCBPQZIQ%2F20170612%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20170612T144818Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Signature=59ecc4d11b7ed71bd336531bd7f4ab7c84da6b7424878d6487679c97a8c52ca7
In this, if try to download the file by using a static path like
$file="./img/user-icon.png";
return \Response::download($file);
it is downloaded fine. But not possible to downloading file from AWS URL, Please help me how to down file automatically using URL. Or How to get Path from URL in laravel or PHP.
Thank you.
Using the above function all the files are being downloaded. But while trying to open the files, text, pdf, ... files open (.text, .csv, .pdf..) without problem, but images don't.
$fileContent = file_get_contents($filePath);
$response = response($fileContent, 200, [
'Content-Type' => 'application/json',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
]);
return $response;

Categories