Laravel Firebase image upload assign URL - php

$bucket=$db122->bucket('sale-purchase-f56ba.appspot.com');
$file1=fopen($request->image, 'r');
$obj=$bucket->upload(
$file1,[
'resumable' => true,
'name' => $filename,
'uploadType'=> "media",
'predefinedAcl' => 'publicRead',
]
);
plz guide me how to give them a URL after upload image, It also lacks Access Token My uploaded image in Storage also not displaying in Storage

You can use the code snippet below to retrieve a signed url to the image uploaded
$expiresAt = new \DateTime('tomorrow');
$storageObject = app('firebase.storage')->getBucket()->object($firebase_storage_path.$name.'.'.$extension);
if ($storageObject->exists()) {
$imageURL = $storageObject->signedUrl($expiresAt);
} else {
$imageURL = '';
}
return $imageURL;
You can change the expiration period if you wish.

Related

How to delete the image from the storage in laravel?

I am currently trying to delete an image when a user updates his/her post before publishing.
Everything works fine, the image is changed in the database and post page, but I want to delete the previous image.
Here is my controller
public function updatePost(Request $request){
$data = $request->all();
$postid = $request['id'];
$isExist = Post::where('id', $postid)->first();
if($isExist){
if ($request->hasFile('image')) {
$file = $request->File('image');
//Get filename with extension
$fileNameToStoreWithExt = $file[0]->getClientOriginalName();
//Get just filename
$filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
//Get just ext
$extension = $file[0]->getClientOriginalExtension();
//File to store
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
//Upload Image
$path = $file[0]->storeAs('image', $fileNameToStore);
$file[0]->move('storage/image', $fileNameToStore);
File::delete(public_path('storage/image'.$isExist['image']));
Post::where('id', $postid)->update([
'title' => $data['title'],
'category' => $data['category'],
'content' => $data['content'],
'image' => $path
]);
return response()->json([
'status'=>'200',
'response'=> 'successfully updated'
]);
}else{
Post::where('id', $postid)->update([
'title' => $data['title'],
'category' => $data['category'],
'content' => $data['content']
]);
return response()->json([
'status'=>'200',
'response'=> 'successfully updated'
]);
}
}else{
return response()->json([
'error'=> 'post does not exist'
]);
}
}
I used:
File::delete(public_path('storage/image'.$isExist['image']));
but it didn't do the job
my delete function
public function deletePost($id){
$post = Post::where('id',$id)->first();
// dd($post);
if(!$post){
return response()->json([
'status' => '500',
'error' => 'post not found'
]);
}
Storage::disk('public')->delete('/storage/image'. $post['image']);
Post::where('id', $id)->delete();
return response()->json([
'status'=> '200',
'response'=> 'Post successfully deleted'
]);
}
my storage path snapshot
use Illuminate\Support\Facades\Storage;
Storage::delete('file.jpg'); // delete file from default disk
Storage::delete(['file.jpg', 'file2.jpg']); // delete multiple files
Storage::disk('your_disk')->delete('file.jpg'); // delete file from specific disk e.g; s3, local etc
Please refer link https://laravel.com/docs/6.x/filesystem
If you look at laravel file-system documentation you will see there are multiple Disk laravel support. you can used Storage Facades to delete a file from Storage like this
use Illuminate\Support\Facades\Storage;
Storage::disk('local')->delete('folder_path/file_name.jpg');
path should be like this for public directory.
Storage::disk('local')->delete('public/image/'.$filename);
its easy to do an if statement and delete old image on updating! this code is an example edit it to your requirements.
if ($request->hasFile('file')) {
Storage::delete($myImage->file); // If $file is path to old image
$myImage->file= $request->file('file')->store('name-of-folder');
}
Another :
File::delete(public_path('images/'. $oldFilename));
see here : https://laracasts.com/discuss/channels/laravel/delete-old-image-from-public-folder-after-updating
You can use normal PHP delete file keyword #unlink
if (file_exists($image)) {
#unlink($image);
}
You can use File to delete file from specific path
$file= "image path here";
\File::delete($file);
Delete uploaded file from public dir
OR
You can use unlink for the same
$image_path = "image path here";
if (file_exists($image_path)) {
#unlink($image_path);
}
PHP -> unlink

How to return the random S3 filename upon Laravel upload?

I am trying to upload video from my Laravel application to my S3 bucket. The uploads are working just fine, but now I want to grab the url of the file, and store it in the database record as well.
Currently, I can upload the file, and store what I think is the url from S3 in the database. None of that is a problem. What happens though is that S3 generates that random file name. I am fine with that, but I would like to return it to the controller somehow so that I can store it with the path in the db.
I am using:
Laravel 5.8.19
An S3 Bucket
league/flysystem-aws-s3-v3
Here is my controller:
public function store(Request $request)
{
//Validate Form Data
$this->validate($request, [
'opponent' => 'required',
'location' => 'required',
'date' => 'required',
'team_id' => 'required',
'season_id' => 'required',
'team_score' => 'required',
'opponent_score' => 'required',
'uploading_coach' => 'required',
'periods' => 'required',
'period_length' => 'required',
]);
//Store all the text fields, not the video
$game = new Game;
$game->opponent = $request->input('opponent');
$game->location = $request->input('location');
$game->date = $request->input('date');
$game->team_id = $request->input('team_id');
$game->season_id = $request->input('season_id');
$game->team_score = $request->input('team_score');
$game->opponent_score = $request->input('opponent_score');
$game->uploading_coach = $request->input('uploading_coach');
$game->periods = $request->input('periods');
$game->period_length = $request->input('period_length');
$game->save();
//Set up some variables needed below
$getGameID = $game->id;
$team_id = $game->team_id;
$game_date = $game->date;
//Handles the actual file upload to S3
$theFile = $request->file('video_file');
$name = 'game_date-' . $game_date . 'game_id-' . $getGameID;
$theFile->storePublicly(
'gameid:' . $getGameID . 'teamid:' . $team_id . '/' . $name,
's3'
);
//Game film is now uploaded to S3, trying to get the url and store it in the db
$url = Storage::disk('s3')->url('gameid:' . $getGameID . 'teamid:' . $team_id . "/" . $name);
$gameVid = Game::find($getGameID);
$gameVid->video_link = $url;
$gameVid->save();
return back();
}
Any ideas?
I had looked at this post before I made mine, but I misunderstood my problem, thinking that his one was unrelated. Turns out the answer to this question is found here: Laravel S3 image upload creates a folder with the filename automatically
The simplest way to upload and retrieve files from S3 is using the Storage facade.
Storage::disk('s3')->put('file.txt', $fileContent);
To upload the file to Amazon S3. The file is stored with the name you provided, so you have a predictable filename. You can save the filename for example in the database so you can later retrieve it.
Then you can later retrieve the saved file with:
Storage::disk('s3')->get('file.txt');
$yourFile = $request->file('<your request name for file>');
$extension = $yourFile->getClientOriginalExtension();
$newName = <new name> . $extension;
Storage::disk('s3')->put("<make a path if you want in to be saved in a folder>".$newName , file_get_contents($yourFile ), 'public');

How to get the image from bucket to preview it to the user

I am working on Google Cloud Storage in which I am trying to crop and upload an image. In this I've uploaded the image and fetching it back to crop it. I have used following methods to do so:
Method 1:
$options = ['gs_bucket_name' => $my_bucket];
$upload_url = CloudStorageTools::createUploadUrl('/upload/handler', $options);
using these docs. But in this I get class not found. I tried including the file for example:
require_once APPPATH."google/appengine/api/cloud_storage/CloudStorageTools.php";
$options = ['size' => 400, 'crop' => true];
$image_file = "gs://my_bucket/shiva.jpg";
$cloud_tools = new CloudStorageTools;
$img = $cloud_tools->getImageServingUrl($image_file, $options);
but the I get class not found for
use google\appengine\CreateEncodedGoogleStorageKeyRequest;
ans etc. I checked the CreateEncodedGoogleStorageKeyRequest under the appengine folder. I found it missing there. I don't know whats going on.
Method 2:
I tried uploading the file using the following code.
function upload_user_image($image_file, $bucket_name = ''){
$client = google_set_client();
$storage = new Google_Service_Storage($client);
$sfilename = $image_file['name']; //filename here
$obj = new Google_Service_Storage_StorageObject();
$obj->setName($sfilename);
$obj->setBucket("my_bucket"); //bucket name here
$filen = $image_file['path'];
$mimetype = mime_content_type($filen);
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$status = false;
$filetoupload = array('name' => $sfilename, 'uploadType' => 'resumable');
$request = $storage->objects->insert("my_bucket",$obj,$filetoupload);
$media = new Google_Http_MediaFileUpload($client, $request, $mimetype, null, true, $chunkSizeBytes);
$media->setFileSize(filesize($filen));
$handle = fopen($filen, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
$result = false;
if($status != false) {
$result = $status;
}
fclose($handle);
// Reset to the client to execute requests immediately in the future.
$client->setDefer(false);
return true;
}
I got succeed in uploading the image using above code but now stuck in getting the image and previewing it in html. (I want to crop the image and then upload again). For which I tried following:
Method a:
$image = file_get_contents("https://storage.cloud.google.com/my_bucket/shiva.jpg");
echo $image;
using these docs. In which I get a login box in my html where I fill my Google credentials and get redirected to image. But don't get the image preview in my html code.
Method b:
I tried
https://www.googleapis.com/storage/v1/b/my_bucket/o/shiva.jpg
using these docs. But I get output :
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Anonymous users does not have storage.objects.get access to object my_bucket/shiva.jpg.",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Anonymous users does not have storage.objects.get access to object my_bucket/shiva.jpg."
}
}
Method c:
I tried it using the following function:
function get_user_image($image_file){
$instance = &get_instance();
// $client = google_set_client();
// $storage = new Google_Service_Storage($client);
$sfilename = $image_file; //filename here
$storage = new Google\Cloud\Storage\StorageClient(['projectId' => $instance->config->item('google_project_id')]);
$bucket = $storage->bucket('my_bucket');
$object = $bucket->object($sfilename);
$stream = $object->downloadAsString();
$im = imagecreatefromstring($stream);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
}
using these docs
I am stuck fro last three days. I need to display the image to user in html. Please anyone guide me what am I missing? Please give the proper way to accomplish this.
Since you are comfortable with these objects being anonymously visible, the easiest solution to display them as images on a website would be simply to mark them as publicly accessible and then to embed them in HTML like so:
<IMG SRC="https://storage.googleapis.com/BUCKET_NAME/imageName.jp‌​eg" />

PHP image upload to Amazon s3 error: cannot be displayed because it contains errors

I'm uploading an image from PHP to Amazon S3 servers.
It is stored successfully but I am not able to open the image ; I am getting this error:
The image “https://s3.amazonaws.com/buckename/24aaffa670e634a7da9a087bfa83abe6_400x400.png” cannot be displayed because it contains errors.
This is my code:
$sourcePath = $_FILES['filedata']['tmp_name'];
$actual_image_name='dinesh'.$_FILES['filedata']['name'];
$contentType= $_FILES['filedata']['type'];
S3::putObject($sourcePath,
BUCKETNAME,
baseName($actual_image_name),
S3::ACL_PUBLIC_READ,array(),
array('Content-Type' =>$contentType))
$value="SampleVideo1.mp4";
$disk = \Storage::disk('s3');
if ($disk->exists($value))
{
$command = $disk->getDriver()->getAdapter()->getClient()->getCommand(
'GetObject', [
'Bucket' => \Config::get('filesystems.disks.s3.bucket'),
'Key' => $value,
]);
$request = $disk->getDriver()->getAdapter()->getClient()->createPresignedRequest($command, '+10 minutes');
$generate_url = $request->getUri();
echo $generate_url;
}

Get Photo_ID in PHP SDK

How do i get the Photo_ID from an photo which my app uploaded with the PHP SDK Code:
$facebook->setFileUploadSupport(true);
$img = '/tmp/mypic.png';
$photo = $facebook->api(‘/me/photos’, ‘POST’,
array( ‘source’ => ‘#’ . $img,
‘message’ => ‘Photo uploaded via the PHP SDK!’
));
Didnt see that it will give any response.
The response of a successful upload is the id of the photo, example:
{
"id": "1001207389476"
}
So $photo should hold a similar value.

Categories