Livewire: What is the proper way to save multiple images in the storage link and the name of the image in the database? - laravel-8

I tried to upload multiple images and want to save it to the storage and and name of the image into database but nothing happened next.
I dump the data from the view and I got this
array:3 [▼
0 => Livewire\TemporaryUploadedFile {#1437 ▼
+"disk": "local"
#storage: Illuminate\Filesystem\FilesystemAdapter {#1384 ▶}
#path: "livewire-tmp/pALAWPNYcMg4pm1w8EINqvURTuYH8x-metaRmFjZWJvb2stMDAxOS5qcGc=-.jpg"
-test: false
-originalName: "pALAWPNYcMg4pm1w8EINqvURTuYH8x-metaRmFjZWJvb2stMDAxOS5qcGc=-.jpg"
-mimeType: "application/octet-stream"
-error: 0
#hashName: null
path: "C:\Windows\Temp"
filename: "pALAWPNYcMg4pm1w8EINqvURTuYH8x-metaRmFjZWJvb2stMDAxOS5qcGc=-.jpg"
basename: "phpB58F.tmp"
pathname: "C:\Windows\Temp\phpB58F.tmp"
extension: "tmp"
realPath: "C:\wamp64\www\cbcc-website\storage\app\livewire-tmp/pALAWPNYcMg4pm1w8EINqvURTuYH8x-metaRmFjZWJvb2stMDAxOS5qcGc=-.jpg"
size: 554154
writable: false
readable: false
executable: false
file: false
dir: false
link: false
}
1 => Livewire\TemporaryUploadedFile {#1438 ▶}
2 => Livewire\TemporaryUploadedFile {#1436 ▶}
]
and this is my store function
public function store(){
dd($this->gallery_image);
$action = '';
$data = $this->validate([
'gallery_image.*' => 'image|max:1024',
]);
if(!empty($this->gallery_image)){
foreach ($this->gallery_image as $images) {
$images->store('Gallery');
}
}
if($this->galleryId){
Gallery::find($this->galleryId)->update($data);
$action = 'edit';
}else{
Gallery::create($data);
$action = 'store';
}
$this->emit('showEmitedFlashMessage', $action);
$this->resetInputFields();
$this->emit('refreshParent');
$this->emit('closeGalleryModal');
}
Is there any better way to this? Thank you.

First of all, make sure you're using WithFileUploads in your component.
It doesn't look like you're saving the files to disk anywhere in your code, all you're doing is recording the file upload to the database.
This is how I'm doing it for a thing I just wrote. In this scenario the public variable uploaded files is wire:bound to your image field, and setup step is the entity that the files table is referencing. My code calls this to actually store the files to disk. It's not complete, because i don't have thumbnail resizing in yet, but it should still give you a good idea of how to do it.
public function saveUploadedFiles() {
if (!empty($this->uploaded_files)) {
foreach ($this->uploaded_files as $file) {
$this->active_file = new File;
$this->active_file->filetype = $file->getMimeType();
$this->active_file->filename = Str::uuid()->toString();
$this->active_file->filesize = $file->getSize();
$this->active_file->order = 0;
$this->active_file->filepath = '/files/setupsteps/' . $this->active_file->filename;
if (strpos($this->active_file->filetype, 'mage') !== false) {
$this->active_file->thumbnail = '/files/thumbnails/setupsteps/' . $this->active_file->filename;
} else {
$this->active_file->thumbnail = asset('images/placeholder.jpg');
}
$this->active_file->created_by = auth()->id();
$this->active_file->updated_by = auth()->id();
$this->uploadFile($file);
$this->active_step->files()->save($this->active_file);
}
$this->active_step->touch();
$this->files = $this->active_step->files;
}
}
public function uploadFile($file) {
$file->storeAs('files/setupsteps/',$this->active_file->filename,'public');
if (strpos($this->active_file->type,'image') !== false){
$file->storeAs('files/thumbnails/setupsteps/',$this->active_file->filename,'public');
}
}

Related

Regenerate missing package-lock.json file from node_modules

The original developers for my project didn't commit the package-lock.json file, only the package.json file. I created my own package-lock.json file when I did npm install, but that was 5 years ago and I didn't realise at the time that I needed to check the file into Git because I stupidly assumed that the original developers knew what they were doing.
Now we have a second developer, plus I need to add a new package. Both of these things require that I have the "original" package-lock.json file.
Is there a way to reconstruct the package-lock.json file using npm from the contents of my node_modules directory which is now the only source of truth? I have looked at various answers and tried a few npm commands, such as npm i --package-lock-only, but that gave me a file as it would be created today, not the file based on my node_modules directory.
So, not finding an answer, I've spent the last two days writing some PHP code to do the job for me. The code is not complete, for example it assumes that the only production modules will be angular and angular-ui-router because I didn't need anything more complicated with my project. However, it's good enough to create an exact copy of the package-lock.json file, minus optional dependencies that weren't installed, because it can't resolve versions of packages it can't find.
The code was written to work, not necessarily to be easy to understand, so it might be a little opaque.
It's run with:
<?php
$package_lock = new PackageLock();
// or
$package_lock = new PackageLock('path/to/packages');
The code:
<?php
class PackageLock {
protected const MY_PACKAGE = 'my-package';
protected const MY_VERSION = '0.0.0';
//
protected const FILE_NAME = 'package-lock-recreated.json';
protected const NODE_MODULES = 'node_modules';
//
protected array $modules = [];
protected array $packages = [
'name' => PackageLock::MY_PACKAGE,
'version' => PackageLock::MY_VERSION,
'lockfileVersion' => 1,
'requires' => true,
];
protected string $dir;
public function __construct(string $dir = '.') {
$this->dir = $dir;
$this->packages['dependencies'] = $this->parse();
file_put_contents(PackageLock::FILE_NAME, preg_replace('/^( +)\1/m', '$1', json_encode($this->packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)));
}
protected function parse(array $priors = []): array {
$nm = PackageLock::NODE_MODULES;
$requests = $priors;
array_unshift($requests, '');
$current_priors = $requests;
$current_priors[] = '';
$main_path = $this->dir . implode("/{$nm}/", $current_priors);
$dir_pattern = $main_path . '*';
$dirs = glob($dir_pattern);
$current_dir = dirname($dir_pattern, 2);
$dependencies = [];
foreach ($dirs as $dir) {
$module_name = basename($dir);
if (in_array($module_name, ['angular-moment-picker', 'json-loader', 'moment-timezone'])) {
continue;
}
$this->modules[$dir] = json_decode(file_get_contents("{$dir}/package.json"));
}
foreach ($this->modules as $dir => $module) {
if (strpos($dir, $main_path) !== 0) {
continue;
}
$module_name = basename($dir);
$dependencies[$module_name] = [
'version' => $module->version,
'resolved' => $module->_resolved,
'integrity' => $module->_integrity,
];
if (!$this->is_prod($module_name)) {
$dependencies[$module_name]['dev'] = true;
}
if ($this->is_optional($main_path . $module_name)) {
$dependencies[$module_name]['optional'] = true;
}
if (!empty($module->dependencies) && (array)$module->dependencies) {
$dependencies[$module_name]['requires'] = $module->dependencies;
}
if (is_dir("{$current_dir}/{$nm}/{$module_name}/{$nm}")) {
$dependencies[$module_name]['dependencies'] = $this->parse_dependencies($priors, $module_name);
}
}
return $dependencies;
}
protected function is_prod($module_name): bool {
return in_array($module_name, ['angular', 'angular-ui-router']);
}
protected function parse_dependencies(array $priors, string $module_name): array {
$priors[] = $module_name;
return $this->parse($priors);
}
protected function is_optional($key): bool {
$module_name = basename($key);
$is_optional = false;
if (!array_key_exists($key, $this->modules)) {
var_dump("Key does not exist: {$key}");
}
if ($this->modules[$key]) {
foreach ($this->modules[$key]->_requiredBy as $parent_module_path) {
if (in_array($parent_module_path, ['/', '#USER', '#DEV:/'])) {
break;
}
$parent_module_path = $this->module_to_file_path($parent_module_path);
if (array_key_exists($parent_module_path, $this->modules)) {
$is_optional = $this->check_optional($parent_module_path, $module_name);
}
else {
$file_name = "{$parent_module_path}/package.json";
if (!file_exists($file_name)) {
$is_optional = true;
}
else {
$this->modules[$parent_module_path] = json_decode(file_get_contents($file_name));
$is_optional = $this->check_optional($parent_module_path, $module_name);
unset($this->modules[$parent_module_path]);
}
}
if (!$is_optional) {
break;
}
}
}
return $is_optional;
}
protected function module_to_file_path($module_path): string {
return $this->dir . str_replace('/', '/' . PackageLock::NODE_MODULES . '/', $module_path);
}
protected function check_optional(string $parent_module_path, $module_name): bool {
if (
!empty($this->modules[$parent_module_path]->optionalDependencies)
&& property_exists($this->modules[$parent_module_path]->optionalDependencies, $module_name)
) {
$is_optional = true;
}
else {
$is_optional = $this->is_optional($parent_module_path);
}
return $is_optional;
}
}

Extendscript Photoshop: Is there a way to save out jpeg with specific KB file sizes for web?

I'm trying to utilize the following. what this does is saves out Jpeg accordingly to less then a a certain size set. I was curious if anyone knew a way to specifically direct a filename to get a filesize that is equal to the following or as close as possible.
Filename_160x600.png = Filename_160x600.jpg 39kb
Filename_300x600.png = Filename_300x600.jpg 59kb
Filename_1500x513.png = Filename_1500x513.jpg 150kb
saveJPG(
{
path: activeDocument.path,
maxSize: 50 //size in kbs
})
function saveJPG(_data)
{
if (_data.path == undefined) return false;
_data.name = _data.name == undefined ? activeDocument.name : _data.name;
_data.quality == undefined && _data.quality = 75;
if (!new Folder(_data.path).exists)
{
alert("Output path doesn't exist!"); //you can add a function to create a path if needed
return false
}
var options = new ExportOptionsSaveForWeb(),
jpgFile = new File(_data.path + '/' + getName(_data.name) + '.jpg');
options.format = SaveDocumentType.JPEG;
options.quality = _data.quality;
activeDocument.exportDocument(jpgFile, ExportType.SAVEFORWEB, options);
if (_data.maxSize != undefined)
{
var ms = _data.maxSize * 1000;
if (jpgFile.length > ms)
{
if (!jpgFile.remove())
{
alert('Save file is locked, please make sure it\'s not opened anywhere');
return
};
saveJPG(
{
path: _data.path,
name: _data.name,
maxSize: _data.maxSize,
quality: _data.quality - 2
});
}
};

My file not in uploads directory after upload was successful

I try to upload file using Yii2 file upload and the file path was successful saved to the database but the file was not saved to the directory I specify.. below is my code..
<?php
namespace backend\models;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;
use Yii;
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $image;
public $randomCharacter;
public function rules(){
return[
[['image'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg'],
];
}
public function upload(){
$path = \Yii::getAlias("#backend/web/uploads/");
$randomString = "";
$length = 10;
$character = "QWERTYUIOPLKJHGFDSAZXCVBNMlkjhgfdsaqwertpoiuyzxcvbnm1098723456";
$randomString = substr(str_shuffle($character),0,$length);
$this->randomCharacter = $randomString;
if ($this->validate()){
$this->image->saveAs($path .$this->randomCharacter .'.'.$this->image->extension);
//$this->image->saveAs(\Yii::getAlias("#backend/web/uploads/{$randomString}.{$this->image->extension}"));
return true;
}else{
return false;
}
}
}
The controller to create the fileupload
namespace backend\controllers;
use Yii;
use backend\models\Product;
use backend\models\ProductSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\UploadForm;
use yii\web\UploadedFile;
public function actionCreate()
{
$addd_at = time();
$model = new Product();
$upload = new UploadForm();
if($model->load(Yii::$app->request->post())){
//get instance of the uploaded file
$model->image = UploadedFile::getInstance($model, 'image');
$upload->upload();
$model->added_at = $addd_at;
$model->image = 'uploads/' .$upload->randomCharacter .'.'.$model->image->extension;
$model->save();
return $this->redirect(['view', 'product_id' => $model->product_id]);
} else{
return $this->render('create', [
'model' => $model,
]);
}
}
Does it throw any errors?
This is propably permission issue. Try changing the "uploads" directory permission to 777 (for test only).
You load your Product ($model) with form data.
if($model->load(Yii::$app->request->post()))
But Uploadform ($upload) never gets filled in your script. Consequently, $upload->image will be empty.
Since you declare 'skipOnEmpty' => false in the file validator of the UploadForm rules, the validation on $upload will fail.
That is why your if statement in the comments above (if($upload->upload()) doesn't save $model data.
I don't see why you would need another model to serve this purpose. It only complicates things, so I assume its because you copied it from a tutorial. To fix and make things more simple, just do the following things:
Add property to Product model
public $image;
Add image rule to Product model
[['image'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg'],
Adjust controller create action
public function actionCreate()
{
$model = new Product();
if($model->load(Yii::$app->request->post()) && $model->validate()) {
// load image
$image = UploadedFile::getInstance($model, 'image');
// generate random filename
$rand = Yii::$app->security->generateRandomString(10);
// define upload path
$path = 'uploads/' . $rand . '.' . $image->extension;
// store image to server
$image->saveAs('#webroot/' . $path);
$model->added_at = time();
$model->image = $path;
if($model->save()) {
return $this->redirect(['view', 'product_id' => $model->product_id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Something like this should do the trick.
Your UploadForm class is already on Backend so on function upload of UploadForm Class it should be like this:
Change this line:
$path = \Yii::getAlias("#backend/web/uploads/");
to this:
$path = \Yii::getAlias("uploads")."/";

how to add an image to product in prestashop

i have a pragmatically added product in my code , the product is added to presta correctly but not about its image .
here is some part of my code that i used :
$url= "localhost\prestashop\admin7988\Hydrangeas.jpg" ;
$id_productt = $object->id;
$shops = Shop::getShops(true, null, true);
$image = new Image();
$image->id_product = $id_productt ;
$image->position = Image::getHighestPosition($id_productt) + 1 ;
$image->cover = true; // or false;echo($godyes[$dt][0]['image']);
if (($image->validateFields(false, true)) === true &&
($image->validateFieldsLang(false, true)) === true && $image->add())
{
$image->associateTo($shops);
if (! self::copyImg($id_productt, $image->id, $url, 'products', false))
{
$image->delete();
}
}
but my product have not any image yet
the problem is in copyImg method ...
here is my copyImg function :
function copyImg($id_entity, $id_image = null, $url, $entity = 'products')
{
$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
$watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
switch ($entity)
{
default:
case 'products':
$image_obj = new Image($id_image);
$path = $image_obj->getPathForCreation();
break;
case 'categories':
$path = _PS_CAT_IMG_DIR_.(int)$id_entity;
break;
}
$url = str_replace(' ' , '%20', trim($url));
// Evaluate the memory required to resize the image: if it's too much, you can't resize it.
if (!ImageManager::checkImageMemoryLimit($url))
return false;
// 'file_exists' doesn't work on distant file, and getimagesize make the import slower.
// Just hide the warning, the traitment will be the same.
if (#copy($url, $tmpfile))
{
ImageManager::resize($tmpfile, $path.'.jpg');
$images_types = ImageType::getImagesTypes($entity);
foreach ($images_types as $image_type)
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'],
$image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
else
{
unlink($tmpfile);
return false;
}
unlink($tmpfile);
return true;
}
can anybody help me ?
You have 2 issues:
You are passing 5th parameter (with value) to copyImg, while the function does not have such.
Your foreach ($images_types as $image_type) loop must include the Hook as well (add open/close curly braces).
foreach ($images_types as $image_type)
{
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'], $image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
You should also check if the product is imported correctly, expecially the "link_rewrite" and if the image is phisically uploaded in the /img/ folder.

Codeigniter Multiple file upload and thumbnail creation: only one thumbnail being uploaded

I am able to upload my images ok, I am able to create thumbnails ok, but only the first thumbnail is being uploaded. I checked the error code for the resize function and they all say 'true' (Success). However, if I upload 4 files, only the first is being uploaded to the thumbnail folder. Here is my code:
function _upload_them_images($_FILES, $last_insert_id)
{
$error = '';
// for($i=0; $i<count($_FILES); $i++)
for($i=0; $i<count($_FILES['imagefile']['name']); $i++)
{
$_FILES['userfile']['name'] = $_FILES['imagefile']['name'][$i];
$_FILES['userfile']['type'] = $_FILES['imagefile']['type'][$i];
$_FILES['userfile']['tmp_name'] = $_FILES['imagefile']['tmp_name'][$i];
$_FILES['userfile']['error'] = $_FILES['imagefile']['error'][$i];
$_FILES['userfile']['size'] = $_FILES['imagefile']['size'][$i];
$config['file_name'] = $last_insert_id.'_'.time().rand(1000,9999).$i;
$config['upload_path'] = './images/vehicles/';
$config['allowed_types'] = 'jpg|jpeg|gif|png';
$config['max_size'] = '1000';
$config['overwrite'] = FALSE;
$this->upload->initialize($config);
if($this->upload->do_upload())
{
$upload_result = $this->upload->data();
$rc = $this->_image_name_into_database(
$last_insert_id,
$upload_result['file_name']);
$image_config = array(
'source_image' =>$upload_result['full_path'],
'new_image' => './images/vehicles/thumbs/',
'create_thumb' => TRUE,
'maintain_ratio' => TRUE,
'width' => 75,
'height' => 50
);
$this->load->library('image_lib', $image_config);
$resize_rc = $this->image_lib->resize();
$error += 0;
}
else
{
//if the image was not uploaded successfully, try resizing
$error += 1;
}
}
if($error > 0)
{
return FALSE;
}
else
{
return TRUE;
}
}
Your image library parameters aren't being updated in the loop. When you call $this->load->...., duplicate items are ignored. You should instead re-initialize the image library with:
$this->image_lib->clear();
$this->image_lib->initialize($image_config);
Before each ->resize()