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
Related
i have 2 web systems here,system a and system b.when i upload an image on system a i want as well send the image to system b.i am using an api to achieve the logic.am able to upload the image in system a perfectly but its unable be pushed to system b.am using guzzle http client to send the image to the api on upload.the upload on system a works very well but the data is being saved in system b.i have tested the api store function in postman and i get i 200ok status code but the data isnt being saved in the specific table in system b database.
here is my image save function in system a which works perfectly,it generates a folder which stores the image and a thumbnail folder inside the main folder where the thumbnail is stored.
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$product_details = product::where('systemid', $request->product_id)->first();
if (!$product_details) {
throw new \Exception('product_not_found', 25);
}
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
if (!in_array($extension, array(
'jpg', 'JPG', 'png', 'PNG', 'jpeg', 'JPEG', 'gif', 'GIF', 'bmp', 'BMP', 'tiff', 'TIFF'))) {
return abort(403);
}
$filename = ('p' . sprintf("%010d", $product_details->id)) . '-m' . sprintf("%010d", $company_id) . rand(1000, 9999) . '.' . $extension;
$product_id = $product_details->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail(
public_path() . "/images/product/$product_id/" . $filename,
$dest,
200);
$systemid = $request->product_id;
$product_details->photo_1 = $filename;
$product_details->thumbnail_1 = 'thumb_' . $filename;
$product_details->save();
// push image to system b on saving
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_h2image";
$response = $client->request('POST',$url,[
'multipart' => [
[
'Content-type' => 'multipart/form-data',
'name' => $filename,
'contents' => file_get_contents( public_path() . "/images/product/$product_id/".$filename)
],
]
]);
} else {
return abort(403);
}
} catch (\Exception $e) {
if ($e->getMessage() == 'validation_error') {
return '';
}
if ($e->getMessage() == 'product_not_found') {
$msg = "Error occured while uploading, Invalid product selected";
}
{
$msg = $e->getMessage();
}
$data = view('layouts.dialog', compact('msg'));
}
return $data;
}
here is my route for the api
Route::post(/push_productimage','APIController#savesystemAimage')->name(pushproductimage');
here is the api function in system b where the image and thumbnail should be recieved and stored to system b database
public function savesystemAimage(Request $request)
{
$productdetails=new Product;
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$filename = ('p' . sprintf("%010d", $productdetails->id)) . '-m' . rand(1000, 9999) . '.' . $extension;
$product_id = $productdetails->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail( public_path() . "/images/product/$product_id/" . $filename,
$dest,200);
$systemid = $request->product_id;
$productdetails->photo_1 = $filename;
$productdetails->thumbnail_1 = 'thumb_' . $filename;
$productdetails->save();
}
}
i dont know why the api function is not storing the data yet on postman it shows a 200ok status code but the image and thumbnail isnt saved.
While updating the user image unlink image from public folder if exists otherwise do update the user with image. Currently I have no image for user. And while updating user from profile section I am getting this error unlink('images/users') is a directory. I want if image exists for user then unlink the image and upload the new one otherwise just upload the new image.
My controller:
public function changeUserImage(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png|max:10000',
]);
$image = $request->file('image');
if (isset($image)) {
$imageName = time() . '.' . $request->image->getClientOriginalExtension();
if (!file_exists('images/users')) {
mkdir('images/users', 0777, true);
}
if (file_exists('images/users')){
unlink('images/users/' . \auth()->user()->image);
$image->move('images/users', $imageName);
User::find(\auth()->user()->id)->update(['image'=>$imageName]);
}else if (!file_exists('images/users')){
$image->move('images/users', $imageName);
User::find(\auth()->user()->id)->update(['image'=>$imageName]);
}
}
return redirect()->back();
}
Try this. I haven't test it yet. Let me know if you have any questions.
Make sure to Import File: use File;
UPDATED
public function changeUserImage(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png|max:10000',
]);
// Let get the current image
$user = Auth::user();
$currentImage = $user->image;
// Let compare the current Image with the new Image if are not the same
$image = $request->file('image');
// The Image is required which means it will be set, so we don't need to che isset($image)
if ($image != $currentImage) {
// To make our code cleaner let define a directory for DRY code
$filePath = public_path('images/users/');
$imageName = time() . '.' . $request->image->getClientOriginalExtension();
if (!File::isDirectory($filePath)){
File::makeDirectory($filePath, 0777, true, true);
}
$image->move($filePath, $imageName);
// After the Image has been updated then we can delete the old Image if exists
if (file_exists($filePath.$currentImage)){
#unlink($filePath.$currentImage);
}
} else {
$imageName = $currentImage;
}
// SAVE CHANGES TO THE DATA BASE
$user->image = $imageName;
$user->save();
return redirect()->back();
}
To store the image: $request->image->storeAs('images/users/', $file_name);
To delete an image: Storage::delete('images/users/'. $file_name);
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);
}
}
I want upload image file on server & want to stored image in database.
How can I store image file in database & also get the image file from database. Please help to solved this problem.
i have done this code in project..
but when uploading image on server upload_path not found.
In controller
$config['upload_path'] = base_url().'aplication/upload/'; // the uploaded images path
$config['allowed_types'] = 'jpg|jpeg|png';/*types of image extentions allowed to be uploaded*/
$config['max_size'] = '3048';// maximum file size that can be uploaded (2MB)
$this->load->library('upload',$config);
if ( ! is_dir($config['upload_path']) ) /* this checks to see if the file path is wrong or does not exist.*/
{
echo( $config['upload_path']);
die("THE UPLOAD DIRECTORY DOES NOT EXIST"); // error for invalid file path
$this->load->library('upload',$config); /* this loads codeigniters file upload library*/
}
if ( !$this->upload->do_upload() )
{
$error=array('error'=>$this->upload->display_errors());
//echo "UPLOAD ERROR ! ".$this->upload->display_errors(); //image error
// $this->load->view('main_view',$error);
}
else
{
$file_data=$this->upload->data();
$data['img']=base_url().'.application/upload/'.$file_data['file_name'];
echo("Image upload successfully..");
//================================================
// $this->load->model('insert_model');
// $this->insert_model->submit_image();
//==========================================
//$this->insert_model->insert_images($this->upload->data());
// $this->load->model('insert_model');
//$this->insert_model->submit_image();
}
That is quite easy. Just create image upload function once in your controller. Here is one function I wrote:
function image_upload($path, $size, $width, $height, $new_name, $ext)
{
$config['upload_path'] = $path;
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = $size;
$config['file_name'] = time() . $new_name . "." . $ext;
$config['max_width'] = $width;
$config['max_height'] = $height;
$this->load->library('upload', $config); //Load codeigniter's file upload library
if (!$this->upload->do_upload())
{
return false;
} else
{
return $config['file_name'];
}
}
Now in the action function of form where you have file input field call this function as follows do as follows:
if ($_FILES['userfile']['name'] != "")//Check if file was selected by the user
{
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);//Get the extension of file
$picture_name = $this->image_upload("your/upload/directory/", 10000, 10000, 100000, "test", $ext);
//Now save this $picture_name in database
}
else
{
print_r($this->upload->display_errors());//Display errors if file does not get uploaded successfully
}
Thats it.
Read This, then you will get how to upload file.
Now how to store it into DB.!
In controller use this :
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$img_data = array('upload_data' => $this->upload->data());
$full_url = "/uploads/".$img_data['upload_data']['file_name'];
$reply = $this->model_name->upload_image($full_url);
}
In model using upload_image($full_url) function store image name with path, so that you can get back that path whenever needed.
I am using Fineuploader for an ajax upload of changing a users profile picture, I have part of my upload.php file below:
function handleUpload($uploadDirectory, $replaceOldFile = FALSE){
if (!is_writable($uploadDirectory)){
return array('error' => "Server error. Upload directory isn't writable.");
}
if (!$this->file){
return array('error' => 'No files were uploaded.');
}
$size = $this->file->getSize();
if ($size == 0) {
return array('error' => 'File is empty');
}
if ($size > $this->sizeLimit) {
return array('error' => 'File is too large');
}
$pathinfo = pathinfo($this->file->getName());
$filename = $pathinfo['filename'];
//$filename = md5(uniqid());
$ext = #$pathinfo['extension']; // hide notices if extension is empty
if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
$these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
}
$ext = ($ext == '') ? $ext : '.' . $ext;
if(!$replaceOldFile){
/// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . DIRECTORY_SEPARATOR . $filename . $ext)) {
$filename .= rand(10, 99);
}
}
$this->uploadName = $filename . $ext;
if ($this->file->save($uploadDirectory . DIRECTORY_SEPARATOR . $filename . $ext)){
return array('success'=>true);
} else {
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
}
so if the image is uploaded with the same name, it creates a duplicate with a number so if asd.jpg is uploaded twice its asd44.jpg .. but I can not find how to make a variable to get the image path with random number created.
Only the initial name of the file that was uploaded. Does anyone know how to go about doing this and then making the update statement to send to database?