I'm having a problem using Storage::disk('s3')->put() to store files to AWS S3 in laravel.
I am writing an api to upload files, everything works fine in the local environment, but when I deploy to the server it doesn't work, and the server returns a 500 error and there is no data in response
This is my code:
public static function uploadFile($file = null, $folder = null){
try {
$bucket = '';
if (empty($file->getClientOriginalName()) || empty($file->getSize())) return ResponseHelpers::clientBEErrorResponse('File Empty !', '');
if ((substr($folder, 0, 1) != '/') && !empty($folder)) $folder = '/' . $folder;
$ex_file = explode('.', $file->getClientOriginalName());
$extent = strtolower($ex_file[(count($ex_file) - 1)]);
unset($ex_file[(count($ex_file) - 1)]);
if (in_array($extent, ['jpg', 'jpeg', 'png', 'gif', 'xlsx', 'docs', 'pdf', 'docx', 'ppt', 'pptx'])) {
$uploadDir = $bucket . $folder.'/'. Str::slug($ex_file[0]).'-'.time().'.'.$extent;
if (in_array($ex_file[0], ['jpg', 'jpeg', 'png'])){
$image = \Image::make(file_get_contents($file));
$upload = Storage::disk('s3')->put($uploadDir, $image->encode('jpeg', 50));
} else{
$upload = Storage::disk('s3')->put($uploadDir, file_get_contents($file));
}
if ($upload){
return ResponseHelpers::showResponse([
'preview' => env('AWS_URL').$uploadDir,
'path' => $uploadDir
], '');
}
return ResponseHelpers::serverErrorResponse();
} else {
return ResponseHelpers::clientBEErrorResponse('Please Select File Type JPG, JPEG, PNG, GIF, XLSX, DOCS Too Upload', '');
}
} catch (\Exception $ex) {
return ResponseHelpers::serverErrorResponse($ex->getMessage(), '');
}
}
I can't even catch the error using try catch.
I tried using this function to upload files when using form with html in blade file view and strangely it still works. Looks like it only crashes when it's an API. I have checked and compared the input data of both ways, they are exactly the same.
Everything stops working when running here: Storage::disk('s3')->put($uploadDir, file_get_contents($file))
Response is completely empty and doesn't have any data or anything
Please check for me. Thanks
Related
I am trying to use google vision API for the image to text converter. I don't know how to use key.json file in the controller. can someone assist?
if($request->file('image')){
//convert image to base64
$image = base64_encode(file_get_contents($request->file('image')));
//Sending image for OCR server
$vision = new VisionClient(['keyFile' => json_decode(file_get_contents("key.json"), true)]);
$familyPhotoResource = fopen($_FILES['image']['tmp_name'], 'r');
$image = $vision->image($familyPhotoResource,
[
'DOCUMENT_TEXT_DETECTION'
]);
$result = $vision->annotate($image);
dd($result);
}
First of all please check that VisionClient credentials.json file is accessible you can check buy dumping like
dd(json_decode(file_get_contents('credentials.json'), true));
if output is look like this then its mean file is accessible https://i.imgur.com/QdMPgCZ.png
if still not working then try this
try{
$vision = new VisionClient(['keyFile' => json_decode(file_get_contents('credentials.json'), true)]);
$image = $vision->image($IMAGE_URL,['Text_Detection']);
$annotation = $vision->annotate($image);
$textAnnotations = $annotation->info();
if( isset($textAnnotations['textAnnotations']) )
foreach ($textAnnotations['textAnnotations'] as $key => $textAnnotation) {
$image_text = $textAnnotation['description'];
break;
}
dd($image_text);
}catch(\Exception $e){
dd("Text Not Detected!");
}
Good day,
I have been running into this exception "Laminas\Diactoros\Exception\InvalidArgumentException: Invalid stream reference provided in file" while trying to upload a video file taken from the camera with react-native-image-picker. Now i ran into this same issue while trying to upload photos some days back till i switched from using "$file->move()" to using "Intervention Image". I dont really understand the error and need some help.
EDIT: I should also mention that when i used postman to upload, it was successful.
Thanks
public function save_verification_video(Request $request) {
/**
* 'file' => 'mimes:video/x-ms-asf,video/x-flv,video/mp4,application/x-mpegURL,video/MP2T,video/3gpp,video/quicktime,video/x-msvideo,video/x-ms-wmv,video/avi'
*/
try {
$validator = $this->validator($request->all(), [
'glam_id' => '',
]);
if ($validator['failed']) {
return \prepare_json(false, ['messages' => $validator['messages']],'',$status_code=200);
}
$data = $request->all();
if ($request->hasFile('body_video') || $request->hasFile('speech_video')) {
// $this->out->writeln("User ".$user->last_name);
$file = $request->file('body_video') ?? $request->file('speech_video');
$verification_type = ($request->hasFile('body_video')) ? 'body_video' : 'speech_video';
$path = public_path('/uploads/glams/'. $user->code . '/videos/'.$verification_type . '/');
File::makeDirectory($path, $mode=0777, true, true);
// $res = MediaUploader::fromFile($file)->upload();
$res = $file->move($path, $file->getClientOriginalName());
if ($res) {
return \prepare_json(true, [],\get_api_string('generic_ok'), $status_code=200);
}
else {
return \prepare_json(false, [],\get_api_string('file_not_ploaded'), $status_code=200);
}
}
else {
return \prepare_json(false, [],\get_api_string('no_videos'), $status_code=200);
}
}
catch(\Illuminate\Database\Eloquent\ModelNotFoundException $ex) {
return \prepare_json(false, [], \get_api_string('glam_not_found'));
}
catch(\Exception $ex) {
return \prepare_json(false, [],\get_api_string('error_occured').$ex->getMessage(), $status_code=200);
}
}
file upload directory not created in my vps its show me blank page in error massege
Here is my code.
$dir_exist = true; // flag for checking the directory exist or not
if (!is_dir('./assets/uploads/profile_pictures/' . $id))
{
mkdir('./assets/uploads/profile_pictures/' . $id, 0777, true);
$dir_exist = false; // dir not exist
}
if ( ! $this->upload->do_upload('upload_profile_picture'))
{
if(!$dir_exist)
rmdir('./assets/uploads/profile_pictures/' . $id);
$error = array('error' => $this->upload->display_errors());
//$this->session->set_flashdata('error', $error[1]);
print_r($error);
}
else
{
$upload_data = $this->upload->data();
$new_name=$upload_data['file_name'];
//$this->session->set_flashdata('error', $data[1]);
}
if($new_name=='0'){
$new_name=$temp_profile_pic;
}
$date = str_replace( ':', '', $date);
if (!is_dir('uploads/'.$date)) {
mkdir('./uploads/' . $date, 0777, TRUE);
}
Please try above code and check if this code is working then definately the issue is different.
and check the id is not getting : either it will never created new dir.
Here is the reference: https://www.socketloop.com/tutorials/codeigniter-php-create-directory-if-does-not-exist-example
I am trying to store an image in cakephp 3.0. I am only able to save the filename in db, however, unable to store the actual file on the server. Need help
Form:
echo $this->Form->create('User', array('url' => array('action' => 'create'), 'enctype' => 'multipart/form-data'));
echo $this->Form->input('upload', array('type' => 'file'));
Images controller:
*/
public function add()
{
$image = $this->Images->newEntity();
//Check if image has been uploaded
if(!empty($this->request->data['Images']['upload']['name']))
{
$file = $this->request->data['Images']['upload']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img' . $file['name']);
//prepare the filename for database entry
$this->data['Images']['image'] = $file['name'];
}
}
if ($this->request->is('post')) {
$image = $this->Images->patchEntity($image, $this->request->data);
if ($this->Images->save($image)) {
$this->Flash->success('The image has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The image could not be saved. Please, try again.');
}
}
$this->set(compact('image'));
$this->set('_serialize', ['image']);
}
For those who are looking for the answer just modify this line :
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img' .DS. $file['name']);
DS is a Directory Separator.
Welcome on stackoverflow!
Please check this question:
cakePHP 3.0 uploading images
This will help you, it's a good plugin for uploading images:
http://cakemanager.org/docs/utils/1.0/behaviors/uploadable/
I am developing a module of epaper in codeigniter(PyroCMS).
I want to know how can I upload multiple images ar once.
Can anyone guide me in uploading multiple images?
I tried but I only found code for uploading single image which I have already used in news module.
In the view file give this code for image upload:
echo form_label('Multi Images','',$label_attr);
echo form_upload($multi_photo_attr);
where
$multi_photo_attr = array(
'id' => "cat_multi_images",
'class' => "multi",
'name' => "cat_multi_images[]",
'maxlength' => "25",
'multiple' => "multiple"
);
Now you need to create a folder in the root directory where your photos will be uploaded.
After that in the controller's method you need to store the path to that folder in a variable.This variable will be used to upload the images in the folder.
Next,get the names of all the images in a array something like this:
foreach($_FILES["cat_multi_images"] as $key => $value)
{
$i=0;
foreach($value as $key1 => $value1)
{
$multi_photo_array[$i][$key] = $value1;
$i++;
}
After that for every array element,i.e.,for every image run the below code to upload it:
function UploadFile($files,$path)
{
$extensions = array('jpeg','JPEG','gif','GIF','png','PNG','jpg','JPG','pdf','PDF','ZIP','zip','rar','RAR','html','HTML','TXT','txt','doc','docx','DOC','DOCX','ppt','PPT','pptx','PPTX','xlsx','XLSX','xls','XLS','exe','EXE','mp3','MP3','wav','WAV','m4r','M4R','mpeg','MPEG','mpg','MPG','mpe','MPE','mov','MOV','avi','AVI',);
$destination = $path.$files["name"];
//print_r($destination);exit;
// GET FILE PARTS
$fileParts = pathinfo($files['name']);
$file_name = $files['name'];
$file_name_only = $fileParts['filename'];
$file_name_only = preg_replace('/[^a-zA-Z0-9]/','',$file_name_only);
$file_extention = $fileParts['extension'];
$Count = 0;
$destination = $path.$file_name_only.".$file_extention";
$file_name = $file_name_only.".$file_extention";;
// THIS SHOULD KEEP CHECKING UNTIL THE FILE DOESN'T EXISTS
while( file_exists($destination))
{
$Count += 1;
$destination = $path. $file_name_only."-".$Count.".$file_extention";
$file_name = $file_name_only."-".$Count.".$file_extention";
}
$fileextension='';
$filename='';
if(!empty($files))
{
$filename=$files['name'];
$fileextension=substr($filename,strpos($filename,".")+1);
if(in_array($fileextension,$extensions))
{
$uploadstatus=move_uploaded_file($files["tmp_name"],$destination);
if($uploadstatus)
{
return $file_name;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
Just copy the above code.It should work as it is made for a general case by me!You can copy that code in your model file and call it in the controller like this :
$pr_photo_data = $this->admin_model->UploadFile($value,$targetPath_images);
$photo_list[] = $pr_photo_data;
And then store every image in the database
foreach($photo_list as $image)
{
$pro_image["cat_multi_images"] = $image;
$pro_retId = $this->admin_model->add_multipic_cat($pro_image);
}
where
function add_multipic_cat($data)
{
$retId = $this->database->query_insert("photo", $data);
return $retId;
}
Be careful.Take care and do every step accurately
check this one
https://github.com/blueimp/jQuery-File-Upload/wiki/jQuery-File-Upload,---Multi-file-upload-with-CodeIgniter
Struggling To Use PyroCMS Files Library To Upload Multiple Files