How can I retrieve the file extension of an image while uploading?
I don't have any problems with the upload, just retrieving the files extension , which would be useful when creating thumbnails dynamically.
Thanks
http://codeigniter.com/user_guide/libraries/file_uploading.html
$this->upload->data()
This is a helper function that returns an array containing all of the data related to the file you uploaded. Here is the array prototype:
Array
(
[file_name] => mypic.jpg
[file_type] => image/jpeg
[file_path] => /path/to/your/upload/
[full_path] => /path/to/your/upload/jpg.jpg
[raw_name] => mypic
[orig_name] => mypic.jpg
[client_name] => mypic.jpg
[file_ext] => .jpg
[file_size] => 22.2
[is_image] => 1
[image_width] => 800
[image_height] => 600
[image_type] => jpeg
[image_size_str] => width="800" height="200"
)
So after the user has uploaded something, you probably want to store the file extension in your database along with other details about the image :-)
$name_of_file_with_extn = $this->upload->data('file_name')
you can change the item name from the below list
file_name Name of the file that was uploaded, including the filename extension
file_type File MIME type identifier
file_path Absolute server path to the file
full_path Absolute server path, including the file name
raw_name File name, without the extension
orig_name Original file name. This is only useful if you use the encrypted name option.
client_name File name as supplied by the client user agent, prior to any file name preparation or incrementing
file_ext Filename extension, period included
file_size File size in kilobytes
is_image Whether the file is an image or not. 1 = image. 0 = not.
image_width Image width
image_height Image height
image_type Image type (usually the file name extension without the period)
image_size_str A string containing the width and height (useful to put into an image tag)
This might help you.
After you uploaded the file, you can get its property by:
$saved_file_name = $this->upload->data('file_name');
// will give you the filename along with the extension
If you want to get only the file extension before uploading it, use core PHP:
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
or to make it clean
$filename= $_FILES["file"]["name"];
$file_ext = pathinfo($filename,PATHINFO_EXTENSION);
Related
Am trying to upload images in laravel 8 but for large files this fails.
In my controller i have the following
public function uploadTemporaryFile(Request $request)
{
$request->validate([
'image' => 'required|mimes:png,jpeg,jpg',
])
$file = $request->file('image');
//do more stuff here
}
The above works for smaller image files but large image files 8MB validation fails. After a bit of troubleshooting and logging the $request on large files i found this to be
var_dump($request);
array (
'image' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'IMG_20201203_072650.jpg',
'mimeType' => 'application/octet-stream',
'error' => 1,
'hashName' => NULL,
)),
)
As per above the large image file the mime type seems to change from image/jpeg to application/octet-stream. The same code used to upload small images is used to upload large image files.
With the application/octet-stream the $request->file("image") is now empty.
How can i get the uploaded file for saving when its a large image file. Or what am i missing.
I have also adjusted both upload_max_filesize and post_max_size to 100M each.
upload_max_filesize
post_max_size
Just put a large value (bigger than the files to be uploaded) on these variables at php.ini.
OBS: modify the correct php.ini file, (FPM, Nginx, Apache, CLI, and correct PHP version), and restart your webserver/fpm. To confirm that you've changed the right file, run:
phpinfo();
And look for those values.
I created Laravel app where I wanted to upload images + resize and crop them, for that I used Invention Image
Here is my code how I'm storing images:
/*just image cropping + resizing*/
$light_image = Image::make($request->file('startup_screenshot'));
$light_image->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});
$light_image->crop(300, 275, 0, 0);
$light_image->encode('jpg');
/*just image cropping + resizing*/
/*image storing*/
$hashed_light_image = md5($light_image->__toString());
$light_image_name = $hashed_light_image . time() . '.jpg';
Storage::put('public/images/startups-screenshots/light_previews/' . $light_image_name, $light_image->__toString());
$path_to_light_image = '/storage/images/startups-screenshots/light_previews/' . $light_image_name;
/*image storing*/
I tried to use this code to delete images but it doesn't work:
...
$startup_to_update = Startup::find($request->id);
Storage::delete($startup_to_update->screenshot);
Storage::delete($startup_to_update->screenshot_light); // pay attention
...
How Can I delete those images ?
Thank you all very much for any ideas!
I realy appreciate this ))
From what you write we can only get conjetures but well, are you sure that you are storing the correct path?, remember that Storage will be storage/app (you can check it in config->filesystem) so it would be stored in
storage/app/public/images/startups-screenshots/light_previews/ . $light_image_name
But for what i can see/think you are looking inside of
/storage/images/startups-screenshots/light_previews/' . $light_image_name
in any case if you think that what is inside $startup_to_update is the real path then you can check if it exist with
Storage::has($direction)
if it return true, then the file exist and you may have a problem with permissions.
ProTip, for these cases i use to make my own disk inside config->filesystems.php
'light_previews' => [
'driver' => 'local',
'root' => storage_path('/app/public/images/startups-screenshots/light_previews/'),
'url' => env('APP_URL').'storage/app/public/images/startups-screenshots/light_previews/',
'visibility' => 'public',
],
And then i use it like these
Storage::disk('light_previews')->put($fileName, file_get_contents($file));//store
Storage::disk('light_previews')->delete($fileName);//delete
You don't have to use intervention to delete images from storage. Intervention only acts as a image helper, not a file system helper.
use Illuminate\Support\Facades\Storage;
Storage::delete(file_path_of_image);
I fixed this, path wasn't correct,
I used this type of path to store my images: "/storage/images/startups-screenshots/light_previews/image_name.jpg" , you can see code example below:
Storage::put('public/images/startups-screenshots/light_previews/' . $light_image_name, $light_image->__toString());
As you can see I used "public/images/...." on the begining, but when I tried to delete this I couldn't because I should point path of that type "public/images/...." , not that one which I used: "/storage/images/...."
so I just changed path from "public/images/...." to "public/images/...."
and it works now
Thanks all for good ideas!
I am struggling a bit with localization in Laravel 5.3 (with php 7). The default localizaiton file format in Laravel 5.3 is using brackets, as in this example:
return [
'footer.contact.email' => 'Email:',
]
That's what I have been using in my app and it's working fine. But now I am trying to work with some packages to help with translations, for example:
https://github.com/potsky/laravel-localization-helpers
https://github.com/barryvdh/laravel-translation-manager
But both of those generate localization files in the "old" laravel 4.x array format. For example
return array(
'footer' => array(
'contact' => array(
'email' => 'Email:',
),
),
);
As I understand it I should have no issue with this localization file format in my laravel 5.3 app, however it's always throwing an exception:
[2016-12-02 13:26:01] local.ERROR: ErrorException: htmlspecialchars() expects parameter 1 to be string, array given in C:\100_source_code\consulting_platform_laravel\maingig\vendor\laravel\framework\src\Illuminate\Support\helpers.php:519
Stack trace:
#0 C:\100_source_code\consulting_platform_laravel\maingig\vendor\sentry\sentry\lib\Raven\Breadcrumbs\ErrorHandler.php(36): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'htmlspecialchar...', 'C:\\100_source_c...', 519, Array)
I really cant understand why this format is not working with my app. I bet it is something trivial that I am missing, but any help would be very welcome!
Thanks,
Christian
After a few extra hours of stepping through the code I found the source of the problem.
For example, I got these in my original lang file:
'footer.subscribe' => 'SUBSCRIBE TO OUR NEWSLETTER',
'footer.subscribe.intro' => 'Be the first to know about our latest news...',
'footer.subscribe.privacy' => 'Privacy Policy',
'footer.subscribe.tos' => 'Terms of Service',
'footer.subscribe.tac' => 'Terms and Conditions',
As I tried to use both of the packages mentioned in my original question they produced the following output:
'footer' =>
array (
'subscribe' =>
array (
'intro' => 'TODO: intro',
'privacy' => 'TODO: privacy',
'tos' => 'TODO: tos',
'tac' => 'TODO: tac',
),
),
As you can see the generated file dropped the value for the text footer.subscribe and only kept the child element, intro, privacy, tos and tas in this case. Therefore a request for trans('footer.subscribe') returns an array and not the text.
Now that I know this I will change the format of my original translation file!
c.
I'm now trying to upload a mp3 file to Soundcloud. Here I'm bogged down to the use of File.new command in Ruby.
I send a request and a passing parameter looks like the below.
Parameters: {..."mp3_1"=>#<ActionDispatch::Http::UploadedFile:0x007ff24d5e3ea8 #tempfile=#<Tempfile:/var/folders/kk/y_wprlln2qv6mzylj03g14x00000gn/T/RackMultipart20160316-21426-14vu8x1.mp3>, #original_filename="datasecurity.mp3", #content_type="audio/mp3", #headers="Content-Disposition: form-data; name=\"mp3_1\"; filename=\"datasecurity.mp3\"\r\nContent-Type: audio/mp3\r\n">}
Then, I write File.new command with the potentail file name and params[:mp3_1] like the below.
client = Soundcloud.new(:access_token => 'XXX')
track = client.post('/tracks', :track => {
:title => 'This is my sound',
:asset_data => File.new("file name",params[:mp3_1])
})
Now I get an error saying:
no implicit conversion of ActionDispatch::Http::UploadedFile into String
The paperclip function works ( storing file to the storage directly has been what I've done ) but this file.new doesn't allow me to move forward. If I can get any help, I really appreciate that (:
Best
you already have a file, no need to create a new one with File.new
have a closer look to your dump :
#tempfile=#<Tempfile:/var/folders/...../RackMultipart20160316-21426-14vu8x1.mp3
this is a file, you may use it directly in your call
client.post('/tracks', :track => {
:title => 'This is my sound',
:asset_data => params[:mp3_1].tempfile)
})
I'm using the (Axlsx gem and it's working great, but I need to add an image to a cell.
I know it can be done with an image file (see Adding image to Excel file generated by Axlsx.?), but I'm having a lot of trouble using our images stored in S3 (through Carrierwave).
Things I've tried:
# image.url = 'http://.../test.jpg'
ws.add_image(:image_src => image.url,:noSelect => true, :noMove => true) do |image|
# ArgumentError: File does not exist
or
ws.add_image(:image_src => image,:noSelect => true, :noMove => true) do |image|
# Invalid Data #<Object ...>
Not sure how to proceed
Try using read to pull the contents into a tempfile and use that location:
t = Tempfile.new('my_image')
t.binmode
t.write image.read
t.close
ws.add_image(:image_src => t.path, ...
To add an alternative answer for Paperclip & S3 as I couldn't find a reference for that besides this answer.
I'm using Rails 5.0.2 and Paperclip 4.3.1.
With image URLs like: http://s3.amazonaws.com/prod/accounts/logos/000/000/001/original/logo.jpg?87879987987987
#logo = #account.company_logo
if #logo.present?
#logo_image = Tempfile.new(['', ".#{#logo.url.split('.').last.split('?').first}"])
#logo_image.binmode # note that our tempfile must be in binary mode
#logo_image.write open(#logo.url).read
#logo_image.rewind
end
In the .xlsx file
sheet.add_image(image_src: #logo_image.path, noSelect: true, noMove: true, hyperlink: "#") do |image|...
Reference link: http://mensfeld.pl/tag/tempfile/ for more reading.
The .split('.').last.split('?').first is to get .jpg from logo.jpg? 87879987987987.