Now I use a simple way to upload images:
if ($request->hasFile("images")) {
$file = $request->file("images");
// Do uploading to Storage
$uploaded = Storage::put($destinationPath. $fileName, file_get_contents($file->getRealPath()));
}
How can I upload multiple files when I have: images[] in HTML form?
Is it possible to do with Storage::put()?
If your form is submitting multiple files under images[] array, you would loop through them accordingly.
It would help if you posted the form html as well.
<?php
$files = $request->file("images");
$uploaded = [];
if($files){
foreach($files as $file) {
$uploaded[] = Storage::put($destinationPath. $fileName, file_get_contents($file->getRealPath()));
}
}
});
In the view (using the LaravelCollective package):
{{ Form::open(['action' => 'MyController#store', 'class' => 'form-horizontal', 'files' => true, 'enctype' => 'multipart/form-data' ]) }}
{{ Form::file('attachments[]', ['class' => 'form-control', 'roles' => 'form', 'multiple' => 'multiple']) }}
{{ Form::close() }}
In the controller:
public function store(Request $request)
{
if (($request->has('attachments'))) {
$files = $request->file('attachments');
$destinationPath = storage_path() . '/app/public/';
foreach ($files as $file) {
$fileName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$storeName = $fileName . '.' . $extension;
// Store the file in the disk
$file->move($destinationPath, $storeName);
}
}
}
Related
After a succesful file upload, my show.blade doesn't seem to find my images to display.
I've already linked the directory and the image uploads directly to the wished directory.
post Controller
public function store(Request $request)
{
/**
* Validation Rules using Validator class
*/
$rules = [
/*'post_id' => 'required|numeric',*/
'title' => 'required|min:3',
'intro' => 'required|min:3',
'content' => 'required|min:3',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
];
$validator = Validator::make($request->all(),$rules);
if($validator->fails()) {
// dd('validation fail');
return Redirect::back()
->withInput()
->with(
[
'notification' =>'danger',
'message' => 'Something went wrong'
]
)
->withErrors($validator);
}
$post = new Post();
$post->title = $request->input('title');
$post->intro = $request->input('intro');
$post->content = $request->input('content');
$success = $post->save();
/**
* Handle image upload
*/
if($request->hasfile('image') && $success){
$directory = '/post-' . $post->id;
foreach($request->file('image') as $image) {
$name = $image->getClientOriginalName();
$extension = $image ->getClientOriginalExtension();
$fileName = pathinfo($name,PATHINFO_FILENAME) . '-' . time() . '.' . $extension;
$image->storeAs($directory,$fileName,'public');
$image = new Image();
$image->post_id = $post->id;
$image->filename = $fileName;
$image->filepath = $directory;
$image->save();
}
return back()->with([
'notification' => 'succes',
'message' => 'You have created a new post'
]);
}
}
Show blade
#extends('layout')
#section('content')
<div>
<h1 class="title">{{$post->title}}</h1>
<p> {{$post->content}} </p>
<div class="row">
#foreach($post->images as $image)
<div class="col-sm">
<img class="img-fluid" src="{{ asset($image->filepath . '/' . $image->filename) }}" alt="{{ $post->title }}">
</div>
#endforeach
</div>
</div>
<p>Edit</p>
#endsection
when i inspect the element, i get the image's alt which is the $post-> title, but the path seems to be incorrect for some reason.
storeAs function returns path to the stored file relative to the storage. You don't need to concatenate it yourself. Also it can be a problem with a forward slash in the path.
// Store result path to the variable
$path = $image->storeAs($directory,$fileName,'public');
$image = new Image();
$image->post_id = $post->id;
$image->filename = $fileName;
$image->filepath = $path; // Save path returned by the storeAs
$image->save();
Use asset with just that path.
<img class="img-fluid" src="{{ asset($image->filepath) }}" alt="{{ $post->title }}">
Also check your file system configuration. public/storage should be symbolic link to the storage/app/public, otherwise stored files will not be accessible from the web.
give this a try.
<img class="img-fluid" src="src="{{ asset('path/to/image/'. $image->filename) }}"" alt="{{ $post->title }}">
I will rather approve it this way
Get the last inserted post ID
$post_id = post->id;
$image = $request->file('image');
if ($request->hasFile('image'))
{
foreach ($request->image as $img) {
$name = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$fileName = $name . '-' . time() . '.' . $extension;
if (!file_exists('POST/IMAGE')) //Let check if the path doesn't exist
{
mkdir('POST/IMAGE', 0777 , true);// then create one with read/write permission
}
$image->move('POST/IMAGE',$imagename); // Save the file in this folder
}else {
$imagename = 'dafault.png'; // Optional: if none file selected, the use default file.
}
$image = new Image();
$image->post_id = $post_idid;
$image->filename = $fileName;
//$image->filepath = $directory;// You don't really need the save the file name in your DB
$image->save();
}
return back()->with([
'notification' => 'succes',
'message' => 'You have created a new post'
]);
}
I want to upload a file in laravel.
I have used this code in controller:
function store1(Request $request){
$file=$request->file('myfile');
$folder=$request->file('folder');
$link=$request->input('link');
$filename1 = $file->getClientOriginalName();
$filename2 = $folder->getClientOriginalName();
//$projectname
$path="files/";
$file->move($path,$filename1);
$folder->move($path,$filename2);
DB::table('groups')->update(['last_report'=>$filename1,'DropBox'=>$filename2]);
return view('successfulUpload');
}
I want to enable user to upload more than one file but it shows Call to a member function getClientOriginalName() on null.
Try this for multiple upload in Laravel.
The HTML form:
<form method="post" action="controller/function" enctype="multipart/form-data">
<input type="file" name="files[]" multiple />
<input type="submit" />
</form>
In your controller:
// get posted input file
$files = Input::file('files');
$errors = "";
$file_data = array();
foreach($files as $file)
{
if(Input::hasFile('files'))
{
// validating each file.
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(
[
'file' => $file,
'extension' => Str::lower($file->getClientOriginalExtension()),
],
[
'file' => 'required|max:100000',
'extension' => 'required|in:jpg,jpeg,bmp,png,doc,docx,zip,rar,pdf,rtf,xlsx,xls,txt'
]
);
if($validator->passes())
{
// path is root/uploads
$destinationPath = 'path/to/upload';
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
if($upload_success)
{
//do after success ....
}
else
{
$errors .= json('error', 400);
}
}
else
{
// redirect back with errors.
return Redirect::back()->withErrors($validator);
}
}
}
I'm trying to display my image (encoded in base64) on my browser.
This is what I had tried:
{{$projects}}
<hr>
#foreach ($projects as $project)
#if ($project['name'] != null)
<p>Project {{ $project['name'] }}</p>
<img src="data:image/{{$project['image_type']}};base64,{{$project['image']}}" alt="Project picture" >
#endif
#endforeach
Which looks like this on the browser link: http://i.imgur.com/U1YUcSo.png
Unfortunately that didn't work out.
Before displaying an image. I had uploaded an image to my database with the following code:
public function store(Request $request)
{
if($request['file'] != null) {
$file = $request['file'];
$fileName = $file->getClientOriginalName();
$imageType = pathinfo($fileName, PATHINFO_EXTENSION);
} else {
$fileName = null;
$imageType = null;
}
Project::create([
'name' => $request['name'],
'content' => $request['content'],
'image' => base64_encode($fileName),
'image_type' => $imageType,
]);
return redirect('/projects');
}
Can someone maybe tell me what I'm doing wrong?
Seems you're encoding the filename in database and not the file contents.
Read about http://php.net/manual/pt_BR/function.file-get-contents.php
(...)
'image' => base64_encode(file_get_contents($fileName)),
Niloct is right.
Insted of
base64_encode($fileName);
you must use
base64_encode(file_get_contents($fileName));
I have file field with required = false, multiple=multiple. Everything works fine, but if file input is empty, symfony2 show me this error.
Error: Call to a member function guessExtension() on null
Here is my form type:
->add('file', 'file', array(
'multiple' => 'multiple',
'data_class' => null,
'required' => false,
'mapped' => false,
'attr' => array(
'maxSize' => '1024k',
'accept' => 'image/*',
)
))
Upload function:
private function uploadImg($files)
{
$path = array();
foreach ($files as $file) {
$extension = $file->guessExtension();
if (!$extension) {
$extension = 'bin';
}
$randomName = 'image' . date('Y-m-d-H-i-s') . uniqid() . '.' . $extension;
$file->move('uploads/images/', $randomName);
$path[] = $randomName;
}
return $path;
}
How can I check if file input is empty?
$form['file']->getData(); every time returns Array
You can use continue to skip empty files
foreach ($files as $file) {
if(!$file) {
continue; //skip
}
$extension = $file->guessExtension();
if (!$extension) {
$extension = 'bin';
}
$randomName = 'image' . date('Y-m-d-H-i-s') . uniqid() . '.' . $extension;
$file->move('uploads/images/', $randomName);
$path[] = $randomName;
}
For Symfony 3, I used this method and working fine.
use Symfony\Component\HttpFoundation\File\UploadedFile;
public function updateAction(...){
// $image is Entity property, change accordingly.
$file = $item->getImage();
if ($file instanceof UploadedFile) {
... upload code
}
}
I'm creating a site using Laravel 4, which allows an admin to upload a large number of images at a time. Currently, I'm able to do just that, where each image is given its own unique ID and put into its own folder named with the same ID.
The problem is that I need the application to also upload a second, resized (smaller) version of the image along with the original. I learned that you must resize an image on the client side, so I'm not sure how I would go about saving the original image, as well as smaller version. The smaller image should be named using the same ID, with some sort of identifier like "-smaller" at the end of the name.
Here's my current front end;
{{ Form::open(array('url' => 'imageUpload', 'files' => true, 'method' => 'post'))}}
<div class="form-group">
<label for="fileToUpload" class="col-sm-2 control-label">Choose All Images</label>
</br>
{{ Form::file('images[]', ['multiple' => true]) }}
</div>
<div class="col-sm-offset-2 col-sm-10">
{{ Form::submit('Add Photos', ['class' => 'btn btn-large btn-primary openbutton'])}}
<!--<button type="submit" class="btn btn-default">Sign in</button> -->
</div>
{{ Form::close() }}
And here's my controller;
$files = Input::file('images');
foreach($files as $file) {
$rules = array(
'file' => 'required|mimes:png,gif,jpeg,txt,pdf,doc,rtf|max:9999999999'
);
$validator = \Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$id = Str::random(14);
$id = $race . "-" . $id;
$destinationPath = 'raceImages/' . $id;
//$filename = $id;
$filename = $file->getClientOriginalName();
$mime_type = $file->getMimeType();
$extension = $file->getClientOriginalExtension();
$upload_success = $file->move($destinationPath, $id);
);
} else {
return Redirect::back()->with('error', 'I only accept images.');
}
}
This is how I resolved the same problem in my app:
Install this package: https://github.com/Intervention/image
Use this code:
$createnew = new Yourmodelname;
$avatar = Input::file('pic_path');
if (isset($avatar)) { //will process the code only if an image was properly pointed in the form
$image = Input::file('pic_path');
var_dump($image->getRealPath()); // just for error tracking
$filename = $image->getClientOriginalName();
if (Image::make($image->getRealPath())->save('foldername/yourprefix_' . $LastInsertId . '_' . $filename)) { } // foldername is related to your public folder
if (Image::make($image->getRealPath())->widen(200)->save('foldername/thumbs/thumb_yourprefix_' . $LastInsertId . '_' . $filename)) {
}
$createnew->pic_path = 'event_poster_' . $LastInsertId . '_' . $filename;
$createnew->pic_thumb = 'event_poster_thumb_' . $LastInsertId . '_' . $filename;
$createnew->save();
}
Now you have two files: one original (no changes) and a thumbnail scaled proportionally to width 280.
Other resize options you can find in the Intervention docs.