简体   繁体   中英

Laravel 4 file upload

I'm trying to upload some photos and handle this with the build in Laravel functions. But I can't for the life of me figure out how to do this properly. I have been able to actually upload something, but I've run into a few problems. This is the code I have right now:

If looked at the documentation, and found this function: $file = Input::file('photo'); I've used this function, and what the content of $file becomes is an instance of Symfony\\Component\\HttpFoundation\\File\\UploadedFile , which, as the documentation tells us, "extends the PHP SplFileInfo class and provides a variety of methods for interacting with the file." http://laravel.com/docs/4.2/requests#files

Then I used this function Input::file('photo')->move($destinationPath); which should but the file in the desired folder on the server. And it did. But now comes the problem. Now all uploaded files have a filename like phpgoJnLc , and without an extension.

I've looked at the functions available from SplFileInfo and tried getExtension which give me an empty string and getFilename which also gives me something like phpgoJnLc .

Then I looked around on the internet and found a few part of code from Laravel 3, where they did something like this:

$filename = Str::random(20) .'.'. File::extension(Input::file('photo.name'));

But the result of this is give me only the result from Str::random(20) followed by a dot. Again, no file extension.

So, what am I doing wrong? How to upload a file with Laravel 4?

Looking in that same class file I see a getClientOriginalName() function...

$file = Input::file('photo');
$file->move($destinationPath,$file->getClientOriginalName());

... which ais ssuming you want to keep the original name your client sets... which could be hazardous, do some safety checks on it would be my advice. Getting the extensionname only is done with ->getClientOriginalExtension() , so you could also only save that part & add a random string before that in the second argument of the move() function.

这对我有用,特别是当您想要更改上传图像的名称时:

$filename = 'New_Name'.'.'.Input::file('photo')->getClientOriginalExtension();

You can also generate a name for the file with the original file extension like so:

$filename = Str::random(20) . '.' . Input::file('image')->guessExtension();

if you try to use the following in Laravel 4:

$filename = Str::random(20) .'.'. File::extension(Input::file('photo.name'));

you will get this error:

'Call to undefined method Illuminate\Filesystem\Filesystem::guessExtension()'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM