How can i change the image upload directory and view image url in laravel - laravel

In my script all images uploaded goes into directory "ib" but i want to change that directory to a different name eg. "imgib"
here is what i did so far. i changed the code vlues from "ib" to "imgib"
} else {
// upload path
$path = 'imgib/';
// if path not exists create it
if (!File::exists($path)) {
File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
}
// move image to path
$upload = $request->file('uploads')->move($path, $imageName);
// file name
$filename = url($path) . '/' . $imageName;
// method server host
$method = 1;
}
// if image uploded
if ($upload) {
// if user auth get user id
if (Auth::user()) {$userID = Auth::user()->id;} else { $userID = null;}
// create new image data
$data = Image::create([
'user_id' => $userID,
'image_id' => $string,
'image_path' => $filename,
'image_size' => $fileSize,
'method' => $method,
]);
// if image data created
if ($data) {
// success array
$response = array(
'type' => 'success',
'msg' => 'success',
'data' => array('id' => $string),
);
// success response
return response()->json($response);
} else {
if (file_exists('imgib/' . $filename)) {$delete = File::delete('imgib/' . $filename);}
// error response
return response()->json(array(
'type' => 'error',
'errors' => 'Opps !! Error please refresh page and try again.',
));
}
so far everything looks ok and it creates "imgib" directory automatically and all uploads go into "imgib" directory.
But the issue is, image url still uses the same old directory name.
eg. site.org/ib/78huOP09vv
How to make it get the correct url eg. site.org/imgib/78huOP09vv

Thanks for the help everyone. I managed to fix the issue by editing viewimage.blade.php
Yes of course need to clear the browser cache after editing the files.

Related

Function wp_generate_attachment_metadata returns always empty array in ajax function

I have searched far and wide, but have not found a solution.
I have a real estate ad insertion form, I need to be able to upload photos of the listings. I can upload the photos to the server via ajax, return the filenames in a textarea and always via ajax, after submitting the form, I can upload the photos to wordpress and attach them to the ad
The only problem is that it does not generate the photo metadata, wp_generate_attachment_metadata always returns an empty array.
I can't find a solution about it. I have another plugin with a similar form, but there I post the form not via ajax, but with the action = "post", and I can safely generate the metadata.
This is the code with which I insert the attachments and link them to the newly created post.
Hope someone can help me
//$filename = domoria-torino-strada-della-fornace-druento-15.jpg
if ($filename != '') {
$wp_upload_dir = wp_upload_dir();
$filename_path = $wp_upload_dir['path'] .'/'. $filename;
$filename_url = $wp_upload_dir['url'] .'/'. $filename;
$guid = $wp_upload_dir['url'] . '/' . basename( $filename_path );
$attachment = array(
'guid'=> $guid,
'post_mime_type' => 'image/jpeg',
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post_id
);
$attach_id = wp_insert_attachment( $attachment, $filename_path);
if($iter === 0){
set_post_thumbnail( $post_id, $attach_id );
}
$ids [] = $attach_id; //this array needs for an ACF field
//filename_path = home/uxo80ef6/domains/homeprime.sviluppo.host/public_html/wp-content/uploads/2021/12/domoria-torino-strada-della-fornace-druento-15.jpg
//$attach_id = 629
$file_uploaded_path = get_attached_file($attach_id);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_uploaded_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
$iter++;
}
UPDATE: The problem is due to getimagesize called by wp_generate_attachment_metadata that can't find the file by file_path, however the file is on the server.
I rewrote some parts of the code you posted:
change hardcoded post_mime_type with wp_check_filetype() instead.
rename some of the variables to: $file_name, $file_path, $parent_post_id
removed unused $filename_url
added $parent_post_id as the third argument into wp_insert_attachment()
removed get_attached_file() function and used $file_path for wp_generate_attachment_metadata()
<?php
// $file_name = domoria-torino-strada-della-fornace-druento-15.jpg
if (!empty($file_name)) {
// The ID of the post this attachment is for.
// eg. $parent_post_id = 37;
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
$file_path = $wp_upload_dir['path'] . '/' . $file_name;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype(basename($file_path), null);
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($file_path),
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_title($file_name),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment($attachment, $file_path, $parent_post_id);
// Set the first attachment as Featured image.
if ($iter === 0) {
set_post_thumbnail($parent_post_id, $attach_id);
}
// ACF field array data.
$ids[] = $attach_id;
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
$iter++;
}

Laravel deleting old image after updating

I want my user's old image to be deleted when they update it. This current function does not work how I want it. How would I change it so it works?
public function update($id)
{
$profile = Profile::findOrFail($id);
$data = request()->validate([
'title' => 'required|max:255',
'image' => ''
]);
if ($profile->image) {
if (Storage::exists("storage/{$profile->image}")) {
Storage::delete("storage/{$profile->image}");
}
}
if (request('image')) {
$imagePath = request('image')->store('profile', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->orientate()->fit(1000, 1000); //Intervention Image Package
$imageArray = ['image' => $imagePath];
$image->save();
}
// $profile->image = $request->image; //Lägg till senare
$profile->update(array_merge(
$data,
$imageArray ?? [],
));
return redirect("/profile/{$profile->user_id}");
}
}
First you have to take the old image and delete it from the server
if (file_exists(('./images/partners/' . $partner->image_path))) {
unlink(('./images/partners/' . $partner->image_path));
}
after that you can upload your new image and update the record in the database

Drupal 8, add an image field from a BuildForm with preview

I created a custom form from a buildForm function. In this form, I would like add an image field.
I can do that via this code :
$form['main']['image'] = array(
'#type' => 'text_format',
'#title' => t('image'),
'#default_value' => array(10),
);
I can upload and remove the image from my form. However, when I upload an image, I haven't this preview.
I mean, when I create a content via the Drupal UI. I can add a preconfigured "image" field. When I upload an image via this "image" field, I have a preview of the image.
And here, when I create the field element programmatically, I haven't a preview of the image when I upload her.
How use api Drupal for have the preview of the image when I upload her via my "image" field ?
So here is how I got my form to display the thumbnail image. What I basically did was take the code in ImageWidget::process, put it in a theme preprocessor and set the #theme property of the element to image_widget.
Your image element in your form class should look like this:
$form['profile_image'] = [
'#type' => 'managed_file',
'#title' => t('Profile Picture'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
'file_validate_size' => array(25600000),
),
**'#theme' => 'image_widget',**
**'#preview_image_style' => 'medium',**
'#upload_location' => 'public://profile-pictures',
'#required' => TRUE,
];
In your name_of_default_theme.theme file, you need the following:
function name_of_default_theme_preprocess_image_widget(&$variables) {
$element = $variables['element'];
$variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));
if (!empty($element['fids']['#value'])) {
$file = reset($element['#files']);
$element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
$file_variables = array(
'style_name' => $element['#preview_image_style'],
'uri' => $file->getFileUri(),
);
// Determine image dimensions.
if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
$file_variables['width'] = $element['#value']['width'];
$file_variables['height'] = $element['#value']['height'];
} else {
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$file_variables['width'] = $image->getWidth();
$file_variables['height'] = $image->getHeight();
}
else {
$file_variables['width'] = $file_variables['height'] = NULL;
}
}
$element['preview'] = array(
'#weight' => -10,
'#theme' => 'image_style',
'#width' => $file_variables['width'],
'#height' => $file_variables['height'],
'#style_name' => $file_variables['style_name'],
'#uri' => $file_variables['uri'],
);
// Store the dimensions in the form so the file doesn't have to be
// accessed again. This is important for remote files.
$element['width'] = array(
'#type' => 'hidden',
'#value' => $file_variables['width'],
);
$element['height'] = array(
'#type' => 'hidden',
'#value' => $file_variables['height'],
);
}
$variables['data'] = array();
foreach (Element::children($element) as $child) {
$variables['data'][$child] = $element[$child];
}
}
The solution works well, but the image module is missing a class with the #FormElement annotation. That is why the element isn't rendered properly.
Can you try with managed_file type?
'#type' => 'managed_file'
First some clarifications, then some observations and then the code that worked for me.
Clarifications:
I am using Drupal 9, but the solution proposed below may work also
for Drupal 8.
By "default temporary directory" I mean the directory defined in the following settings
file
[DrupalrootDirectory]/sites/default/settings.php
using
$settings['file_temp_path'] = '/The/Absolute/Path/To/Your/Temporary/Directory';
or defined by your operating system and that you can check in the Drupal administration
menu:
[YourSiteWebAddress]/admin/config/media/file-system
When something is written inside square brackets [], like this, [DrupalrootDirectory], it means that you should replace it with the actual name in your system, Drupal installation or custom module/file, without the square brackets.
Observations:
No need to create apriory any directories inside the default
temporary directory. They will be created automatically.
When you click the Remove button (which appears automatically as soon you upload a file in your custom form), the image file and the thumbnail files are deleted from the default temporary directory.
It does not matter if you define your default temporary directory inside the default site location,
e.g.,
[DrupalrootDirectory]/sites/default/files
or outside it, for example,
[DrupalrootDirectory]/sites/other/files
In my case, I defined it to:
[DrupalrootDirectory]/sites/default/files/temp
No need to make changes to .htaccess (in Apache server) file inside the default temporary directory or
inside
[DrupalrootDirectory]/sites/default/files
Keep them as Drupal created them.
No need to change file rights to "777" inside the default temporary directory, "775" is enough.
Check that your Drupal installation is actually creating thumbnails for images uploaded using the
administration menu:
[YourSiteWebAddress]/admin/content/media
when using the "Add media" link
[YourSiteWebAddress]/media/add/image
No need to make any other changes inside Drupal settings
file
[DrupalrootDirectory]/sites/default/settings.php
The code that worked for me:
It is based in the code published above by "Je Suis Alrick". But his code was not working for me, neither I could not find in which part of his code the thumbnail image was actually created. In my search for it, this post helped
Generate programmatically image styles with Drupal 8
So, here is the final code:
In your custom module, in the custom form file, most probably located
in:
[DrupalrootDirectory]/modules/custom/[NameOfYourCustomModule]/src/Form/[NameOfYourCustomForm].php
you add the element to be used to upload the image file:
$form['profile_image'] = [
'#type' => 'managed_file',
'#title' => t('Profile Picture'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
'file_validate_size' => array(25600000),
),
'#theme' => 'image_widget',
'#preview_image_style' => 'medium',
'#required' => TRUE,
];
So far, the same as in the code of "Je Suis Alrick", except that I deleted the definition for '#upload_location', so the default temporary directory will be used avoiding security complaints.
The important part here is:
the definition of the '#theme', which may be any name, but in this case is 'image_widget';
and the definition of '#preview_image_style', which must be the machine name of one of the image styles defined in your Drupal installation, that you can check in your administration
menu
[YourSiteWebAddress]/admin/config/media/image-styles
For this case the style 'medium' will be used, which is one of the image styles created by default by Drupal.
Then, in the module file of your custom module, named [NameOfYourCustomModule].module and most probably located
in:
[DrupalrootDirectory]/modules/custom/[NameOfYourCustomModule]/
You will need to paste the following code:
<?php
use Drupal\image\Entity\ImageStyle;
function [NameOfYourCustomModule]_preprocess_image_widget(&$variables) {
$element = $variables['element'];
$variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));
if (!empty($element['fids']['#value'])) {
$file = reset($element['#files']);
$element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
$file_variables = array(
'style_name' => $element['#preview_image_style'],
'uri' => $file->getFileUri(),
);
// Determine image dimensions.
if (isset($element['width']['#value']) && isset($element['height']['#value'])) {
$file_variables['width'] = $element['width']['#value'];
$file_variables['height'] = $element['height']['#value'];
} else {
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$file_variables['width'] = $image->getWidth();
$file_variables['height'] = $image->getHeight();
$style = ImageStyle::load($file_variables['style_name']);
$image_uri = $file->getFileUri();
$destination = $style->buildUri($image_uri);
$style->createDerivative($image_uri, $destination);
}
else {
$file_variables['width'] = $file_variables['height'] = NULL;
}
}
$element['preview'] = array(
'#weight' => -10,
'#theme' => 'image_style',
'#width' => $file_variables['width'],
'#height' => $file_variables['height'],
'#style_name' => $file_variables['style_name'],
'#uri' => $file_variables['uri'],
);
// Store the dimensions in the form so the file doesn't have to be
// accessed again. This is important for remote files.
$element['width'] = array(
'#type' => 'hidden',
'#value' => $file_variables['width'],
);
$element['height'] = array(
'#type' => 'hidden',
'#value' => $file_variables['height'],
);
}
$variables['data'] = array();
foreach (\Drupal\Core\Render\Element::children($element) as $child) {
$variables['data'][$child] = $element[$child];
}
}
You should note that at the end of the name of the function, the name of the theme 'image_widget' is included, which tells Drupal to process your form element using the defined above function: [NameOfYourCustomModule]_preprocess_image_widget
What have I added?
The line at the
top:
use Drupal\image\Entity\ImageStyle;
And the following four lines that actually create the image thumbnail inside the default temporary directory:
$style = ImageStyle::load($file_variables['style_name']);
$image_uri = $file->getFileUri();
$destination = $style->buildUri($image_uri);
$style->createDerivative($image_uri, $destination);
With the addition of these five lines I got it working!
Nice answer thx, only change I'd make is using Token for upload location, and Bytes for file upload size, although I guess it depends on the use case. Something like the below (stripped out most of the code for the sake of simplicity.
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Component\Utility\Bytes;
use Drupal\Core\Utility\Token;
class SampleForm extends FormBase
{
protected $currentUser;
protected $token;
public function __construct(AccountProxyInterface $current_user, Token $token) {
$this->currentUser = $current_user;
$this->token = $token;
}
public static function create(ContainerInterface $container)
{
return new static(
$container->get('current_user'),
$container->get('token')
);
}
/**
* {#inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['sample_image'] = [
'#type' => 'managed_file',
'#title' => t('Profile Picture'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
'file_validate_size' => file_upload_max_size() / pow(Bytes::KILOBYTE, 2) . 'M',
),
'#theme' => 'image_widget',
'#preview_image_style' => 'medium',
'#upload_location' => $this->token->replace('private://[date:custom:Y]-[date:custom:m]'),
'#required' => TRUE,
];
return $form;
}
}
Theme it to work on multiple file upload. From #Je Suis Alrick answer above.
function themename_preprocess_image_widget(&$variables) {
$element = $variables['element'];
$variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));
if (!empty($element['fids']['#value'])) {
foreach ($element['#files'] as $file) {
$element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
$file_variables = array(
'style_name' => $element['#preview_image_style'],
'uri' => $file->getFileUri(),
);
// Determine image dimensions.
if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
$file_variables['width'] = $element['#value']['width'];
$file_variables['height'] = $element['#value']['height'];
} else {
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$file_variables['width'] = $image->getWidth();
$file_variables['height'] = $image->getHeight();
}
else {
$file_variables['width'] = $file_variables['height'] = NULL;
}
}
$element['preview'][] = array(
'#weight' => -10,
'#theme' => 'image_style',
'#width' => $file_variables['width'],
'#height' => $file_variables['height'],
'#style_name' => $file_variables['style_name'],
'#uri' => $file_variables['uri'],
);
// Store the dimensions in the form so the file doesn't have to be
// accessed again. This is important for remote files.
$element['width'] = array(
'#type' => 'hidden',
'#value' => $file_variables['width'],
);
$element['height'] = array(
'#type' => 'hidden',
'#value' => $file_variables['height'],
);
}
}
$variables['data'] = array();
foreach (\Drupal\Core\Render\Element::children($element) as $child) {
$variables['data'][$child] = $element[$child];
}
}

Overwrite file names when uploading catalog images to Magento

When you upload a product image to Magento that has the same name as an existing image, normal behavior for Magento is to append a "_1" to the end of the new file name. So if I have an image named "myFile.png" and upload a second image to the same product with that same name, Magento will rename it to "myFile_1.png". I would like to eliminate this renaming and have files of the same name replace an existing file.
I think I found the relevant controller at: app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php:
public function uploadAction()
{
try {
$uploader = new Mage_Core_Model_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->addValidateCallback('catalog_product_image',
Mage::helper('catalog/image'), 'validateUploadFile');
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$result = $uploader->save(
Mage::getSingleton('catalog/product_media_config')->getBaseTmpMediaPath()
);
Mage::dispatchEvent('catalog_product_gallery_upload_image_after', array(
'result' => $result,
'action' => $this
));
/**
* Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS
*/
$result['tmp_name'] = str_replace(DS, "/", $result['tmp_name']);
$result['path'] = str_replace(DS, "/", $result['path']);
$result['url'] = Mage::getSingleton('catalog/product_media_config')->getTmpMediaUrl($result['file']);
$result['file'] = $result['file'] . '.tmp';
$result['cookie'] = array(
'name' => session_name(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain()
);
} catch (Exception $e) {
$result = array(
'error' => $e->getMessage(),
'errorcode' => $e->getCode());
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
I have tried setAllowedRenameFiles() to false. I have also tried commenting it out. But neither of these seems to give the desired results.
Any thoughts on how I can enable Magento to overwrite existing files of the same name?

Magento custom image upload doesn't work

I need to create an image upload field for posts in Magento Blog Module (AW blog).
Therefore, each post needs to contain an image.
I edited the following files:
/home/clients/websites/w_gale/public_html/gale/app/code/community/AW/Blog/Block/Manage/Blog/Edit/Tab/Form.php
added fieldset like this:
$fieldset->addField('fileinputname', 'image', array(
'label' => Mage::helper('blog')->__('Upload image'),
'required' => false,
'name' => 'fileinputname',
'required' => true,
'style' => 'height:100px;border:2px solid #999;',
));
on top of this file, in the right place, I defined form like this:
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data',
)
);
In Blogcontroller.php I added the following code, just bellow the if ($data = $this->getRequest()->getPost()) { line
if(isset($_FILES['fileinputname']['name']) && (file_exists($_FILES['fileinputname']['tmp_name']))) {
try {
$uploader = new Varien_File_Uploader('fileinputname');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS ;
$uploader->save($path, $_FILES['fileinputname']['name']);
$data['imageurl'] = $_FILES['fileinputname']['name'];
} catch(Exception $e) {
}
} else {
if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1)
$data['imageurl'] = '';
else
unset($data['fileinputname']);
}
However, the upload doesn't work. What am I doing wrong?
I added a special row in appropriate field in a database.
The frontend section displays the database value when I enter it manually.
Thanks
This code of method from data helper which uploads image. You need implement method getBaseDir() (which returns dir where you wish store your uploaded files) by yourself.
/**
* Upload image and return uploaded image file name or false
*
* #throws Mage_Core_Exception
* #param string $scope the request key for file
* #return bool|string
*/
public function uploadImage($scope)
{
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addValidator('ImageSize', true, $this->_imageSize);
$adapter->addValidator('Size', true, $this->_maxFileSize);
if ($adapter->isUploaded($scope)) {
// validate image
if (!$adapter->isValid($scope)) {
Mage::throwException(Mage::helper('mycompany_mymodule')->__('Uploaded image is not valid'));
}
$upload = new Varien_File_Uploader($scope);
$upload->setAllowCreateFolders(true);
$upload->setAllowedExtensions(array('jpg', 'gif', 'png'));
$upload->setAllowRenameFiles(true);
$upload->setFilesDispersion(false);
if ($upload->save($this->getBaseDir())) {
return $upload->getUploadedFileName();
}
}
return false;
}
You're using the right code. I solved the problem by using the right MYSQL data type. When I changed the data type from 'text' to 'varchar(255)' it solved the problem
And ... make sure that you add the following code:
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data',
)
);
in /app/code/community/AW/Blog/Block/Manage/Blog/Edit/Form.php
NOT: app/code/community/AW/Blog/Block/Manage/Blog/Edit/Tab/Form.php

Resources