I am now troubling with this small error. I have a module which is using to upload images. Now this is my code for saving the file. It is defined in saveAction() method of controller.
<?php
/*rest part*/
$postData = $this->getRequest()->getPost();
if(isset($_FILES['banner_img_1']['name']) and (file_exists($_FILES['banner_img_1']['tmp_name'])))
{
try
{
$uploader = new Varien_File_Uploader('banner_img_1'); $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'banner' . DS ;
$uploader->save($path, $_FILES['banner_img_1']['name']);
$postData['banner_img_1'] = $_FILES['banner_img_1']['name'];
}
catch(Exception $e)
{
}
}
else
{
if(isset($postData['banner_img_1']['delete']) &&
$postData['banner_img_1']['delete'] == 1)
$postData['image_main'] = '';
else
unset($postData['banner_img_1']);
}
However this is not storing my image in media/banner folder. When I use path as
<?php
$path = Mage::getBaseDir('media') . DS ;
it saves image in media folder. I dont know the reason why it happens like this. when I print the $path variable, it currectly points towards media/banner folder. What is the error in my code? Please help me to solve this minor error. Thanks in advance..
Try this code in the try block {}
$path = Mage::getBaseDir('media') . DS . 'banner' . DS .'banner'.DS;
$uploader = new Varien_File_Uploader('banner_img_1');
$uploader->setAllowedExtensions(array('jpg','png','gif'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$destFile = $path.$_FILES['banner_img_1']['name'];
$filename = $uploader->getNewFileName($destFile);
$uploader->save($path, $filename);
$post_data['banner_img_1']='banner/banner/'.$filename;
Related
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);
}
After deploying my laravel project from local to Apache web server, all works correctly except images link. Here the code:
Images are stored in:
storage/app/public/photos
after i've run command:
php artisan storage:link
Images are linked at:
public/storage/photos
Controller:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photo = $file->storeAs('public/photos', 'foto-' . time() . '.' . $extension);
$user->photo = $photo;
$user->save();
}
Images are uploaded correctly on storage/app/public/photos and correctly linked in public/storage/photos but it doesn't display on frontend.
in blade, i've tried to use Storage::url to retrieve the path
{{Storage::url($user->photo)}}
and asset()
{{asset($user->photo)}}
in both cases, image doesn't exist
The public path of image is:
http://mywebsite.com/storage/photos/foto-1522914164.png
You should Use url function to show your image like below way.
url($user->photo);
I'd suggest to change the controller code as follows:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'foto-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$user->photo = 'photos/' . $photoFileName;
$user->save();
}
Then you can use {{asset($user->photo)}} in your blade.
on my webspace, it seems that the only way to display image correctly is to create a custom route that read and serve the image.
i'm solved like this:
i'm storing only image name in db:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'photo-' . $model->id . '.-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$store = $photoFileName;
}
then, i've create custom route that read images and display them:
Route::get('storage/{filename}.{ext}', function ($filename, $ext) {
$folders = glob(storage_path('app/public/*'), GLOB_ONLYDIR);
$path = '';
foreach ($folders as $folder) {
$path = $folder . '/' . $filename . '.' . $ext;
if (File::exists($path)) {
break;
}
}
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header('Content-Type', $type);
return $response;
});
in blade, i'm using Storage to display image:
{{ Storage::url($photo->photo) }}}
I'm trying to create multiple copies of profile pic in different sizes when a profile is created. But I am constantly getting this error:
" NotReadableException: Image source not readable"
Can somebody point me what I'm missing in my below code:
public function updateprofile(UserProfileRequest $request){
$user_id = Auth::User()->id;
$profile = UserProfile::where('user_id','=',$user_id)->first();
$profile->fullname = $request->fullname;
if ($request->hasFile('img')) {
if($request->file('img')->isValid()) {
$types = array('_original.', '_32.', '_64.', '_128.');
$sizes = array( '32', '64', '128');
$targetPath = 'public/uploads/'.$user_id;
try {
$file = $request->file('img');
$ext = $file->getClientOriginalExtension();
$fName = time();
$original = $fName . array_shift($types) . $ext;
Storage::putFileAs($targetPath, $file, $original);
foreach ($types as $key => $type) {
$newName = $fName . $type . $ext;
Storage::copy($targetPath . $original, $targetPath . $newName);
$newImg = Image::make($targetPath . $newName);
$newImg->resize($sizes[$key], null, function($constraint){
$constraint->aspectRatio();
});
$newImg->save($targetPath . $newName);
}
$profile->img = 'public/uploads/'.$user_id;
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
$profile->save();}
I had the same issue i ran this command and it worked
php artisan storage:link
This command creates a storage directory under the public folder.
Also use public path function to get the public path
$targetPath = public_path('storage/uploads/'. $user_id);
The 'storage' used inside the laravel public_path() function is used to get the storage main folder.
If I'm not mistaken, the path which is provided should be the absolute filepath on your server. For example instead of:
$targetPath = 'public/uploads/'.$user_id;
Use (your actual path will vary depending on your configuration)
$targetPath = '/var/www/sitename/public/uploads/'.$user_id;
Laravel also contains a helper function called public_path() which can be used to obtain the "fully qualified path to the public directory". This would allow you to use something such as:
$targetPath = public_path('uploads/'. $user_id);
Also, on this line, do not forget to place a slash before the new filename:
$newImg = Image::make($targetPath . '/' . $newName);
I would also confirm that the user executing the script (if apache or nginx usually www-data unless altered) has write permissions to your public/uploads/ directory
Finally, I got it working. I made following changes to my code:
Use the full OS path as suggested by commanderZiltoid for the destination path.
Don't use Storage::putFileAs method to save the file. So, remove this line: Storage::putFileAs($targetPath, $file, $original);
Don't use Storage::copy() to copy the file, so, remove this line:
Storage::copy($targetPath . $original, $targetPath . $newName);
For points 2 and 3, use Image::make($file->getRealPath()); This will create the file and remember the path where the file was created. Image->resize method will use this path later.
In the end, save the relative path in the database, as here: $profile->img = 'storage/uploads/'.$user_id.'/img/profile/'.$fName. Since we'll use {{ asset($profile->img) }}, it's necessary to save only the relative path and not the absolute OS path.
if($request->hasFile('img')) {
if($request->file('img')->isValid()) {
$types = array('_original.', '_32.', '_64.', '_128.');
$sizes = array( array('32','32'), array('64','64'), array('128','128'));
$targetPath = '/Users/apple/Documents/_chayyo/chayyo/storage/app/public/uploads/'.$user_id.'/img/profile/';
try {
$file = $request->file('img');
$ext = $file->getClientOriginalExtension();
$fName = time();
$o_name = $fName . array_shift($types) . $ext;
$original = Image::make($file->getRealPath());
$original->save($targetPath . $o_name);
foreach ($types as $key => $type) {
$newName = $fName . $type . $ext;
$newImg = Image::make($file->getRealPath());
$newImg->resize($sizes[$key][0], $sizes[$key][1]);
$newImg->save($targetPath . $newName);
}
$profile->img = 'storage/uploads/'.$user_id.'/img/profile/'.$fName;
}
catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
I'm trying to make an image upload script with laravel 4. (using Resource Controller) and i'm using the package Intervention Image.
And what i want is: when uploading an image to save it as 3 different images (different sizes).
for example:
1-foo-original.jpg
1-foo-thumbnail.jpg
1-foo-resized.jpg
This is what i got so far.. it's not working or anything, but this was as far as i could get with it.
if(Input::hasFile('image')) {
$file = Input::file('image');
$fileName = $file->getClientOriginalName();
$fileExtension = $file->getClientOriginalExtension();
$type = ????;
$newFileName = '1' . '-' . $fileName . '-' . $type . $fileExtension;
$img = Image::make('public/assets/'.$newFileName)->resize(300, null, true);
$img->save();
}
Hopefully someone can help me out, thanks!
You may try this:
$types = array('-original.', '-thumbnail.', '-resized.');
// Width and height for thumb and resized
$sizes = array( array('60', '60'), array('200', '200') );
$targetPath = 'images/';
$file = Input::file('file')[0];
$fname = $file->getClientOriginalName();
$ext = $file->getClientOriginalExtension();
$nameWithOutExt = str_replace('.' . $ext, '', $fname);
$original = $nameWithOutExt . array_shift($types) . $ext;
$file->move($targetPath, $original); // Move the original one first
foreach ($types as $key => $type) {
// Copy and move (thumb, resized)
$newName = $nameWithOutExt . $type . $ext;
File::copy($targetPath . $original, $targetPath . $newName);
Image::make($targetPath . $newName)
->resize($sizes[$key][0], $sizes[$key][1])
->save($targetPath . $newName);
}
Try this
$file = Input::file('userfile');
$fileName = Str::random(4).'.'.$file->getClientOriginalExtension();
$destinationPath = 'your upload image folder';
// upload new image
Image::make($file->getRealPath())
// original
->save($destinationPath.'1-foo-original'.$fileName)
// thumbnail
->grab('100', '100')
->save($destinationPath.'1-foo-thumbnail'.$fileName)
// resize
->resize('280', '255', true) // set true if you want proportional image resize
->save($destinationPath.'1-foo-resize-'.$fileName)
->destroy();
I am new to magento and i am Creating Custom module for File upload in magento admin.
Right now i have post the upload file in my module controller.
Here i have used move_uploaded_file to upload file in same directory with in controller folder.
below code i have used for file upload in controller
$file_name=$_FILES["file"]["name"];
$file_path="import/$file_name";
if(move_uploaded_file($_FILES["file"]["tmp_name"],$file_path))
{
// my files not uploading
}
I can't able to upload the file in directory folder.
So what i am doing wrong? or suggest me if using move_uploaded_file in magento controller is correct way to handle file upload ?
Thanks.
In order to upload file in Magento, you can use Varien_File_Uploader::save() method as:
if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
try {
$fileName = $_FILES['file']['name'];
$fileExt = strtolower(substr(strrchr($fileName, "."), 1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = str_replace(' ', '', $fileNamewoe) . '.' . $fileExt;
$uploader = new Varien_File_Uploader('file');
$uploader->setAllowedExtensions(array('png', 'jpg')); //allowed extensions
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'yourModuleFolder';
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path . DS, $fileName );
} catch (Exception $e) {
echo $e->getMessage();
}
}