URL has problems in laravel app wihile using S3 on local machine - php

Imagine you've uploaded a file on a S3 bucket or any type of external storage, right? the address might be :
storage.mystie.com/file
and the browser sees this like:
https://storage.mysite.com/file
but the app I'm working on, sends it like this:
//https://storage.mysite.com
and it results in this error:
Error executing "ListObjects" on "//https://IP"; AWS HTTP error: cURL error 6: Could not resolve host:
What's my problem? is it related to my .env file?!

I've implemented "AWS S3" in one of my Laravel's project when I'm going to save user data and upload his profile picture on s3 storage, while updating that image unlink the previous one and then upload the newest picture.
While storing User's Information code was like-this:
$user = User::create([
'first_name' => preg_replace('!\s+!', ' ', ucfirst($user['first_name'])),
'last_name' => preg_replace('!\s+!', ' ', ucfirst($user['last_name'])),
'email' => strtolower($user['email']),
'phone' => $user['phone'],
'address' => $user['address'],
'avatar' => $this->avatar?env('s3').Storage::disk('s3')->put('/profile',$this->avatar,'public'):'',
'type' => 'business',
'password' => bcrypt('business123456789'),
'meta' => $user['meta']
]);
While updating User's Data:
$filne_name = $this->old_avatar;
if($_FILES['avatar']['size'] > 0 && env('image-upload') == 'true')
{
if(!empty($this->old_avatar))
{
$image = pathinfo($this->old_avatar);
$response = Storage::disk('s3')->exists('/profile/'.$image['basename']);
if($response)
{
Storage::disk('s3')->delete('/profile/'.$image['basename']);
}
}
$filne_name = env('s3').Storage::disk('s3')->put('/profile',$this->avatar,'public');
}
return User::where('id',$this->segment(3))->update([
'first_name' => preg_replace('!\s+!', ' ', ucfirst($user['first_name'])),
'last_name' => preg_replace('!\s+!', ' ', ucfirst($user['last_name'])),
'email' => $user['email'],
'phone' => $user['phone'],
'address' => $user['address'],
'avatar' => $filne_name,
'meta' => json_encode($user['meta'])
]);
And in my .env
s3='https://bucket_link.com/' (That was s3 bucket link)

Related

how to solve Illuminate\Contracts\Filesystem\FileNotFoundException: File not found at path on FTP storage laravel?

example image response error File not found at path
hey can you help me?
so here I want to view the image file from the ftp server that will be responded to by JS along with the FTP server link
controller example :
$explode = explode('#',$lampiran->lampiran_gambar);
foreach($explode as $row){
if($row == null){
$row1[] = 'null';
}else{
$row1[] = Storage::disk('ftp')->get('/lampiranSurat' . $row);
}
}
if($pegawai_pejabat->jenis_jabatan_id == 1){
return response()->json([
'meta' => [
'code' => 200,
'status' => 'success',
'message' => 'Data Ditemukan',
],
'data_verifikasi' => $verifikasi,
'lampiran_gambar' => $row1,
'pegawai_verif' => $pegawai_verif,
]);
}
example config filesystem :
'default' => env('FILESYSTEM_DRIVER', 'ftp')
'ftp' => [
'driver' => 'ftp',
'host' => env('FTP_HOST'),
'username' => env('FTP_USERNAME'),
'password' => env('FTP_PASSWORD'),
'root' => '/web',
],
config file .env :
FTP_HOST=exampleftpserver.com
FTP_USERNAME=userftp
FTP_PASSWORD=password123
so why is my ftp url not being read in storage?
for image file data already in the database and already in FTP
You're missing a / between your directory name and the filename:
Replace
$row1[] = Storage::disk('ftp')->get('/lampiranSurat' . $row);
With
$row1[] = Storage::disk('ftp')->get('/lampiranSurat/' . $row);

How to send Image or file to the external API using HTTP Client?

I have an API to save images and files
this is the code to save the image request from the API
$file = $request->file('gambar');
$fileName = $file->getClientOriginalName();
$file->storeAs('images/berita', $fileName);
$berita = new Berita;
$berita->judul = $request->judul;
$berita->kategori_id = $request->kategori_id;
$berita->isi = $request->isi;
$berita->gambar = $fileName;
$berita->tgl = $request->tgl;
$berita->user_id = $request->user_id;
$berita->save();
return response()->json([
'message' => 'Data berita Added Successfully!',
'Added berita' => $berita
], Response::HTTP_OK);
I already try the API in postman, and everything went well, image sucessfully uploaded.
Then on the client side, I'm using HTTP Client from Laravel to POST the data to the API. And here's the code.
$Berita = Http::withToken('xxx')
->attach('attachment', file_get_contents($request->file('gambar')))
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'gambar' => file_get_contents($request->file('gambar')),
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
return $Berita;
All the data send successfully, except the gambar which contains the image that i sent. It says that in my API validation.
The gambar must be a file of type: jpeg, jpg, png.
It thought that means the image that i send is sent as a string, so it didn't receive it as a file.
By the way, here's the Laravel documentation about HTTP Client: https://laravel.com/docs/9.x/http-client#multi-part-requests
Does anyone knows how to correctly using it? I think i've misused it.
I think there is problem with attachment.
return Http::withToken('xxx')
->attach('gambar', file_get_contents($request->file('gambar')), , 'gambar.png')
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
or
return Http::withToken('xxx')
->attach('gambar', $request->file('gambar'), 'gambar.png')
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
This is because the server cannot read your data.
You should send the data using the application/x-www-form-urlencoded content type, you can achieve this as Laravel documentation says:
$response = Http::asForm()->post('http://example.com/users', [
'name' => 'Sara',
'role' => 'Privacy Consultant',
]);

How to set User ID to Storage path in Laravel?

I'm building an Restful API using Laravel 5 and MongoDB.
I'm saving avatar image for users.
It's working fine but I'm trying to create a Folder for every User. For example: "app/players/images/USERID"
I've tried to do something like this in different ways but I always get Driver [] is not supported.
\Storage::disk('players'.$user->id)->put($image_name, \File::get($image));
UploadImage:
public function uploadImage(Request $request)
{
$token = $request->header('Authorization');
$jwtAuth = new \JwtAuth();
$user = $jwtAuth->checkToken($token, true);
$image = $request->file('file0');
$validate = \Validator::make($request->all(), [
'file0' => 'required|image|mimes:jpg,jpeg,png'
]);
if ( !$image || $validate->fails() )
{
$data = array(
'code' => 400,
'status' => 'error',
'message' => 'Image uploading error-'
);
}
else
{
$image_name = time().$image->getClientOriginalName();
\Storage::disk('players')->put($image_name, \File::get($image));
$user_update = User::where('_id', $user->id)->update(['imagen' => $image_name]);
$data = array(
'code' => 200,
'status' => 'success',
'user' => $user->id,
'imagen' => $image_name
);
}
return response()->json($data, $data['code']);
}
filesystems.php:
'players' => [
'driver' => 'local',
'root' => storage_path('app/players/images/'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
I expect the user avatar image saves on User ID folder.
The disk call, tells Laravel which filesystem to use, let's assume you have an user with Id one, with your code it will access the filesystem playeers1.
What usually is done is to put these files in folder structures for the different users, so instead you could do. This will put your image file, in the folder 1.
\Storage::disk('players')->put($user->id . '/' . $image_name, \File::get($image));
I had a similar problem, check if the lines can change what you want to achieve.
\Storage::disk('players')->put("{$user->id}/{$image_name}", \File::get($image));
I relied on the laravel guide: File Storage - File Uploads
I hope it helps you. A cordial greeting.

Laravel/Lumen email trimming for api

I am developing an api using Laravel/Lumen. I have seen very few users are complaining that even though their emails are completely fine, my api response says The email must be a valid email address.
What I have seen is that they are giving a space by mistake after their email like 'noob#user.com '. As a result the email is not accepted by the system. What I'm using in my code so far is:
try {
$this->validate($request, [
'first_name' => 'required|min:3|max:40',
'last_name' => 'required|min:3|max:40',
'email' => 'required|email|unique:clients,email',
'profile_photo' => ''
]);
} catch (ValidationException $e) {
return response()->json($this->clientTransformer->validationFailed($e), 200);
}
I have tried adding the following lines inside the first line of try block but failed to change the $request object property.
try{
$request->email = trim($request->email, ' '); //<= or
$request->email = str_replace(' ', '', $request->email); // <= this line
$this->validate($request, [
'first_name' => 'required|min:3|max:40',
'last_name' => 'required|min:3|max:40',
'email' => 'required|email|unique:clients,email',
'profile_photo' => ''
]);
}
but these arent working. this is passing the exact same email to the validate method. Is there any quick way to do it?
You can use:
$request->replace(array('email' => trim($request->email)));
or
$request->merge(array('email' => trim($request->email)));
Source:
https://laracasts.com/discuss/channels/general-discussion/laravel-5-modify-input-before-validation

Post a blob using Guzzle

Is it possible to post a blob using Guzzle? The only methods I've been able to find are using #filename to upload a local file. The file is stored as a blob in a MySQL database and I would like to upload it to an api as a post field without the redundancy of saving the blob to disk (and the permissions/path issues that come with it), uploading #filename, and then unlinking the file. Here is the code I have that is working for everything but the blob. I need the 'file' field to save the data as a blob.
$data = array(
'first_name' => $fname,
'last_name' => $lname,
'email' => $email,
'partner_key' => 'qwerty',
'secret_key' => 'qwerty',
'file' => $fileblob
);
$curl = new \GuzzleHttp\Client();
return $curl->post('https://www.api.com',['verify'=>false,'body'=>$data])
The goal being to replace the existing cURL code using Guzzle:
'file' => "#".$localfile.";type=".mime_content_type($localfile)
I found the solution. Hopefully this helps others in the future:
$data = array(
'first_name' => $fname,
'last_name' => $lname,
'email' => $email,
'partner_key' => 'qwerty',
'secret_key' => 'qwerty',
'file' => new \GuzzleHttp\Post\PostFile('filename', $fileblob)
);
$curl = new \GuzzleHttp\Client();
return $curl->post('https://www.api.com',['verify'=>false,'body'=>$data])

Categories