Fineuploader: PHP randomized image name variable value - ajax

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?

Related

How to Delete the previous image from the folder when updated by new image in Laravel

**I want to delete the previous image saved in folder and update new image in laravel What is mistake in this code it doesnt work?**xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
code that stores data and image
public function store(Request $request)
{
if($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$request->image->move(public_path('/uploads/image'), $fileNameToStore);
}
else
{
$fileNameToStore = 'No Img Found!';
}
$covidrecord = new Covidrecord();
$covidrecord->fullname = $request->fullame;
$covidrecord->image = $fileNameToStore;
$covidrecord->save();
if( $covidrecord->save())
{
return redirect()->route('store')->with(['msg'=>"User create successfully"]);
return redirect()->route('store')->withError(['msg'=>"User cannot be registerd at the moment"]);
}
}
code to update data and image
public function update(Request $request, $id)
{
$covidrecord = Covidrecord::find($id);
#Check if uploaded file already exist in Folder
if($request->hasFile('product_image'))
{
#Get Image Path from Folder
$path = 'uploads/image/'.$covidrecord->image;
if(File::exists($path))
{
File::destroy($path);
}
#If File is new and not Exist in Folder
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$request->product_image->move(public_path('/uploads/image'), $fileNameToStore);
$covidrecord->product_image = $fileNameToStore;
if($covidrecord->save())
{
dd('Product updated Successfully');
}
else{
dd('Product update Failed');
}
}
}
There is red line in File
The public path method is missing while you are generating a path to check file existence in the update method
$path = public_path().'/uploads/image/'.$covidrecord->image;
if(File::exists($path))
{
File::destroy($path);
}

upload file in public laravel

Hello guys when I use file upload and save link in database it save this "/tmp/phpkPhygr|public/allFiles/files/26657d5ff9020d2abefe558796b99584/69adc1e107f7f7d035d7baf04342e1ca.gif" so why "tmp/php..." show in this link or I want to remove this to work this url.
$files = array();
if($files = $request->file('files')){
foreach($files as $file){
$fileName = md5(rand(100,1000)) . "." . strtolower($file->getClientOriginalExtension());
$folder='public/allFiles/files/' . md5(rand(100,10));
$file_url = $folder . "/" . $fileName;
$file->move($folder, $fileName);
$files[] = $file_url;
}
}
$filesReq = $files;
if($filesReq == ' '){
$filesReq = 'no files';
}else{
$filesReq = implode('|', $files);
}

upload an image through an api using in laravel

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.

how to add uniqid in image upload in laravel

I have a function to insert data in a table and this data includes image/file . I think my form didn't have problem but after I added this uniqid(), it can't be submitted with error "Call to a member function getClientOriginalExtension() on null"
public function store_pelatihan(Request $request)
{
$this->validate($request,[
// 'title' => 'required|min:5',
// 'description' => 'required|min:5|max:14'
] );
if($request->hasfile('file_scan'))
{
$file = $request->file('file_scan');
$name=$file->getClientOriginalName();
$extension = $request->image->getClientOriginalExtension();
$fileName = $file.'.'.uniqid().'.'.$extension;
$file->move(public_path().'/files/', $fileName);
$data = $fileName;
}
$users = new Master_seminar_pelatihan;
$users->user_id = $request->user_id ;
$users->nama_pelatihan = $request->nama_pelatihan ;
$users->nomor_pelatihan = $request->nomor_pelatihan ;
$users->tanggal = $request->tanggal ;
$users->uraian = $request->uraian ;
$users->tempat = $request->tempat ;
$users->file_scan = $data;
dd($data);
// $users->save();
// return redirect ('pelatihan')->with('success', 'Input Succes');
}
Previously, I was running this code and it was running without error:
$extension = $request->image->getClientOriginalExtension();
$fileName = $file.'.'.uniqid().'.'.$extension;
change this line :
$request->image->getClientOriginalExtension()
to :
$file->getClientOriginalExtension()
If you're concatenating with '.' before uniqid() it'll take extension so either you use '-' or '_'.
$fileName = $file.'_'.uniqid().'.'.$extension;
Or
$fileName = $file.'-'.uniqid().'.'.$extension;
Check file isValid() first
Get getClientOriginalExtension() of the $file (not $request->image)
Do not concatenate $file (it is UploadedFile) variable with strings. $name should be instead
if ($request->hasfile('file_scan') && $request->file('file_scan')->isValid()) {
$file = $request->file_scan;
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . uniqid() . '.' . $extension;
$file->move(public_path() . '/files/', $fileName);
$data = $fileName;
}

file upload directory not created in my vps

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

Resources