currently i have base 64 value in
$model->test
and i want to decode the base 64 value in controller and save it to database through API here some of my code in controller
i try to decode and cant figure out how to upload it to server and create path
however i try to to pass the $data to getinstance which is not working
public function doSaveStudent(StudentLoanForm $model)
{
$url = API_URL . 'web/apply/student';
$data1 = $model->test;
$decode = base64_decode($data);
$img = file_put_contents('webcam.jpg', $data);
$model->doUploads();
$ktpdetail = UploadedFile::getInstance($model, 'image_ktp');
$data = null;
$data = [
[
'name' => 'univ_name',
'contents' => $model->univ_name
],
[
'name' => 'test',
'contents' =>$model->test
],
];
// dd($model->test);
if ($ktpdetail != null) {
$data[] = [
'name' => 'image_ktp',
'contents' => fopen(Yii::getAlias('#frontend/web/') . $model->image_ktp, 'r'),
'filename' => $ktpdetail->getBaseName() . '.' . $ktpdetail->getExtension()
];
}
if($ktpayahdetail != null){
$data[] = [
'name' => 'foto_ktp_ayah',
'contents' => fopen(Yii::getAlias('#frontend/web/') . $model->foto_ktp_ayah, 'r'),
'filename' => $ktpayahdetail->getBaseName() . '.' . $ktpayahdetail->getExtension()
];
}
if ($kkdetail != null) {
$data[] = [
'name' => 'image_kk',
'contents' => fopen(Yii::getAlias('#frontend/web/') . $model->image_kk, 'r'),
'filename' => $kkdetail->getBaseName() . '.' . $kkdetail->getExtension()
];
i expect to decode the base 64 and upload all the value using yii2 best practice
The yii\web\UploadedFile is used only for files uploaded using file input in forms.
In your case base64_decode($model->test) should give you binary data of image.
Then you have two options what to do with them.
1) You can store them directly into BLOB attribute in database.
$imageModel = new MyImageModel();
$imageModel->data = base64_decode($model->test);
if(!$imageModel->save()) {
throw new \yii\base\Exception("Couldn't save file to db");
}
2) You can save the file with file_put_contents and then store the path to file in your model.
$imageData = base64_decode($model->test);
//the used alias in path is only example.
//The datetime and random string are used to avoid conflicts
$filename = Yii::getAlias(
'#frontend/web/' . date('Y-m-d-H-i-s') .
Yii::$app->security->generateRandomString(5) . '.jpg'
);
if (file_put_contents($filename, $imageDate === false) {
throw new \yii\base\Exception("Couldn't save image to $filename");
}
$imageModel = new MyImageModel();
$imageModel->path = $filename;
if(!$imageModel->save()) {
//delete file if we couldn't save path into db to prevent creating an orphan
unlink($filename);
throw new \yii\base\Exception("Couldn't add $filename to database");
}
Related
I try to delete the old profilepicture in storage file but it is not working.
below is my screenshot of my files
and this is my code in update profile controller.
public function updateProfile(Request $request, User $user)
{
if ($request->hasFile('profilepicture')) {
Storage::delete('/storage/profilepicture' . $user->profilepicture);
$filenameWithExt = $request->file('profilepicture')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('profilepicture')->getClientOriginalExtension();
$fileNameToStore = time() . '.' . $extension;
$path = $request->file('profilepicture')->storeAs('public/profilepicture', $fileNameToStore);
$user->update([
'profilepicture' => $fileNameToStore
]);
}
$user->update([
'name' => $request->name,
'email' => $request->email,
'birth_date' => $request->birth_date,
'section' => $request->section,
'unit' => $request->unit,
'phone' => $request->phone,
]);
return back()->withSuccess('You have successfully update User.');
}
i already tried
Storage::delete('/public/storage/profilepicture/' . $user->profilepicture);
Storage::delete('/storage/profilepicture/' . $user->profilepicture);
Storage::delete('profilepicture/' . $user->profilepicture);
but none of them is working. Or there is any other correct way to do this?
Use class Filesystem instead of Storage, and give it an absolute path like this:
// Declare
use Illuminate\Filesystem\Filesystem;
// Using
$file = 'icon-256x256.png';
$path = public_path('profilepicture/' . $file);
Filesystem::delete($path);
You will delete the file successful!
i want to send an image from one web system(A) to another web system(B).the image is saved in system(A) and then sent to system(B).am using guzzle http client to achieve this.my api in system (B) works very well as i have tested it in postman.the part i have not understood why its not working is in my system(A) where i have written the guzzle code.i have not seen any error in my system(A) log file but the file isnt sent to system (B).
here is my image save function is system(A).
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
$product_details = product::where('systemid', $request->product_id)->first();
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
$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)
$imageinfo = array(
'file' => $filename,
'product_id' => $product_details->id,
);
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_h2image";
$response = $client->request('POST',$url,[
// 'Content-type' => 'multipart/form-data',
'multipart' => [
[
'name' => 'imagecontents',
'contents' => fopen(public_path() . ("/images/product/$product_id/") . $filename, 'r'),
// file_get_contents(public_path("/images/product/$product_id/thumb/thumb_" . $filename)),
'filename' =>$filename
],
[
'name' => 'imageinfo',
'contents' => json_encode($imageinfo)
],
]
]);
}
}
}
i have followed every step in the documentation but still the process isnt working.where might i be making a wrong move?the laravel version of my project is 5.8 and the version of the guzzle http client is 7.4.1
My file_url field is always erased in Database if I don't select it. (even if an image is already integrated)
If I click Save in this situation, the field PC Image is deleted.
Here is my postImage() method in my AdminCustomController
protected function postImage($id)
{
$file = isset($_FILES['file_url']) ? $_FILES['file_url'] : false;
if ($file && is_uploaded_file($file['tmp_name'])) {
$path = _PS_MODULE_DIR_ . 'custom/img/';
$tmp_arr = explode('.', $file['name']);
$filename = $file['name'];
if (!Tools::copy($file['tmp_name'], $path . $filename)) {
$errors[] = Tools::displayError('Failed to load image');
}
}
}
And here is the renderForm()
public function renderForm()
{
$image_url = '';
if($this->object->file_url) {
$image_url = ImageManager::thumbnail(
_PS_MODULE_DIR_ . 'homecase/img/' . $this->object->file_url,
$this->table . $this->object->file_url,
150,
'jpg',
true,
true
);
}
$this->fields_form = [
//Entête
'legend' => [
'title' => $this->module->l('Edition'),
'icon' => 'icon-cog'
],
array(
'type' => 'file',
'label' => $this->l('PC Image'),
'name' => 'file_url',
'display_image' => true,
'image' => $image_url ? $image_url : false,
),
....
The upload and the save in DB is OK. But when the image exists and I don't select an other in the field. The file_url field is erased in the DB.
Could you help me?
Thanks !
You need to check if an image was uploaded and only after that update your DB records. So, just try to add return false; to your postImagemethod and that check before your DB update like
if ($this->postImage($id) !== false){
//update image record
}
I am using
$this->widget(
'CMultiFileUpload',
array(
'model' => $model,
'attribute' => 'Image',
'accept' => 'jpg|gif|png|doc|docx|pdf',
'denied' => 'Only doc,docx,pdf and txt are allowed',
'max' => 4,
'remove' => '[x]',
'duplicate'=>'Already Selected',
)
);
for upload multiple images , i save all images into database.But i want to download that saved image.
public function uploadMultifile ($model, $attr, $path)
{
/*
* path when uploads folder is on site root.
* $path='/uploads/doc/'
*/
if ($sfile = CUploadedFile::getInstances($model, $attr)) {
foreach ($sfile as $i => $file) {
$fileName = "{$sfile[$i]}";
$formatName=time() . $i . '_' . $fileName;
$file->saveAs(Yii::app()->basePath . '/' . $formatName);
$ffile[$i] = $formatName;
}
return ($ffile);
}
}
I want to provide link to image and download automatically.
echo CHtml::link($data->image);
Any help appreciated.
I tried
public function actionDownloadImage()
{
$model = $this->loadModel($_GET['id']);
$fileDir = Yii::app()->basePath.'/Img/';
Yii::app()
->request
->sendFile(
$model->image,
file_get_contents($fileDir.$model->image),
$model->image
);
}
but give error..
You haven't defined folder path to save image in uploadMultifile() action. So you can't get your desired images from "Img" named folder. You have to make following changes in uploadMultifile() action:
public function uploadMultifile ($model, $attr, $path)
{
/*
* path when uploads folder is on site root.
* $path='/uploads/doc/'
*/
if ($sfile = CUploadedFile::getInstances($model, $attr)) {
foreach ($sfile as $i => $file) {
$fileName = "{$sfile[$i]}";
$formatName=time() . $i . '_' . $fileName;
$file->saveAs(Yii::app()->basePath . '/Img/' . $formatName); // specify folder path where you have to save image
$ffile[$i] = $formatName;
}
return ($ffile);
}
}
Hope this helps.
$model = new XUploadForm;
$model->file = CUploadedFile::getInstance( $model, 'file' );
//We check that the file was successfully uploaded
if( $model->file !== null ) {
//Grab some data
$model->mime_type = $model->file->getType( );
$model->size = $model->file->getSize( );
$model->name = $model->file->getName( );
$file_extention = $model->file->getExtensionName( );
//(optional) Generate a random name for our file
$file_tem_name = md5(Yii::app( )->user->id.microtime( ).$model->name);
$file_thumb_name = $file_tem_name.'_thumb.'.$file_extention;
$file_image_name = $file_tem_name.".".$file_extention;
if( $model->validate( ) ) {
//Move our file to our temporary dir
$model->file->saveAs( $path.$file_image_name );
if(chmod($path.$file_image_name, 0777 )){
// Yii::import("ext.EPhpThumb.EPhpThumb");
// $thumb_=new EPhpThumb();
// $thumb_->init();
// $thumb_->create($path.$file_image_name)
// ->resize(110,80)
// ->save($path.$file_thumb_name);
}
//here you can also generate the image versions you need
//using something like PHPThumb
//Now we need to save this path to the user's session
if( Yii::app( )->user->hasState( 'images' ) ) {
$userImages = Yii::app( )->user->getState( 'images' );
} else {
$userImages = array();
}
$userImages[] = array(
"filename" => $file_image_name,
'size' => $model->size,
'mime' => $model->mime_type,
"path" => $path.$file_image_name,
// "thumb" => $path.$file_thumb_name,
);
Yii::app( )->user->setState('images', $userImages);
//Now we need to tell our widget that the upload was succesfull
//We do so, using the json structure defined in
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
echo json_encode( array( array(
"type" => $model->mime_type,
"size" => $model->size,
"url" => $publicPath.$file_image_name,
//"thumbnail_url" => $publicPath.$file_thumb_name,
//"thumbnail_url" => $publicPath."thumbs/$filename",
"delete_url" => $this->createUrl( "upload", array(
"_method" => "delete",
"file" => $file_image_name
) ),
"delete_type" => "POST"
) ) );
Above code give me correct response,
[{"type":"image/jpeg","size":2266,"url":"/uploads/tmp/0b00cbaee07c6410241428c74aae1dca.jpeg","delete_url":"/api/imageUpload/upload?_method=delete&file=0b00cbaee07c6410241428c74aae1dca.jpeg","delete_type":"POST"}]
but if I uncomment the following
// Yii::import("ext.EPhpThumb.EPhpThumb");
// $thumb_=new EPhpThumb();
// $thumb_->init();
// $thumb_->create($path.$file_image_name)
// ->resize(110,80)
// ->save($path.$file_thumb_name);
it gave me corrupted response:
Mac OS X 2��ATTR�dA��Y�Ycom.apple.quarantine0001;50655994;Google\x20Chrome.app;2599ECF9-69C5-4386-B3D9-9F5CC7E0EE1D|com.google.ChromeThis resource fork intentionally left blank ��[{"type":"image/jpeg","size":1941,"url":"/uploads/tmp/409c5921c6d20944e1a81f32b12fc380.jpeg","delete_url":"/api/imageUpload/upload?_method=delete&file=409c5921c6d20944e1a81f32b12fc380.jpeg","delete_type":"POST"}]
I'm guessing MacOS has quarantined your download of ext.EPhpTHumb.EPhpThumb or one of its libraries.
If you know where the plugin is installed, try xattr -d com.apple.quarantine <filename> from a terminal to remove it, or google remove mac os x quarantine status for alternate ways to do it.