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));
Related
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);
}
}
}
I tried to upload image on my public folder but i constantl getting error like this
The "C:\xampp\tmp\phpCE7B.tmp" file does not exist or is not readable.
Her is my code that i tried so far
public function create(Register $request)
{
//Registering Students
$student=new Student;
$student->name = $request->input('name');
$student->username = $request->input('username');
$student->email = $request->input('email');
$student->password = bcrypt($request->input('password'));
$student->gender = $request->input('gender');
$student->phone = $request->input('phone');
if ($request->hasFile('image')) {
$file=$request->File('image');
$ext=$student->username. "." .$file->clientExtension();
$path = public_path(). '/images/';
$file->move($path,$ext);
$student->image = $ext;
}
$student->save();
}
it saved my info with image in database but after storing gives me the error.Please help me to solve this
"UPDATE"
I dont Know what is happening to me, but now its working autometically
I have the same problem when i'm trying to upload image to public path.
I solved the problem by defining a file system disk in config (filesystems) like that:
'YourDiskName' => [
'driver' => 'local',
'root' => public_path(),
],
then you can upload images to this path by using StoreAs method:
$file = $file->storeAs(YourPathInPublic, YourFileName, [
'disk' => 'YourDiskName'
]);
// Get Form Image
$image = $request->file('image');
$slug = str_slug($request->name);
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
if (!file_exists('storage/uploads/post'))
{
mkdir('storage/uploads/post',0777,true);
}
$image->move('storage/uploads/post',$imagename);
}else{
$imagename = "default.png";
}
//getting coding
public function index(){
return view('admin.post.index',compact('posts'));
}
// show code
<div class="body">
<img class="img-responsive img-thumbnail" src="{{ asset('storage/uploads/post/'.$post->image) }}" >
</div>
I also had the same issue when I use public_path()
Try something like this rather than using public_path. Actually there is nothing wrong with your code. But this happens most of the time due to permission levels. As others said you can try reinstalling Xampp or just try this.
if ($request->hasFile('image')) {
$file = $request->File('image');
$ext = $student->username.".".$file->clientExtension();
$ext->save('your_public_path/'.$ext);
//$path = public_path().'/images/';
//$file->move($path,$ext);
$student->image = $ext;
}
Example code from one of my project for your info
$image = $request->file('uploadUserAvatar');
$fileName = time().'.'.request()->uploadUserAvatar->getClientOriginalExtension() ;
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(300,300);
$image_resize->save(('assets/img/user_avatars/'.$fileName));
I am new in Laravel and I develop a web application where someone can upload a car ad and other users can write comments bellow that. Instead of developing a simple CRUD application I thought about developing also a table that will be related to these ads and will store the photos. Up to this point, I have made the relations, I can show images and I have two problems: The first problem is that not all images are moved to storage/photos folder and the second problem is that all the records in the database have the same name. For example, if I want to upload images 1,2,3 then in the database all the files will have the name 1.
Bellow, you may find the store code. This code stores all the ads and also the images if they exist.
public function store(Request $request)
{
//
$this->validate($request, [
'name' => 'required',
'cc' => 'required',
'desc' => 'required',
'date' => 'required'
]);
$ad = new Ad;
$ad->name = $request->input('name');
$ad->cc = $request->input('cc');
$ad->desc = $request->input('desc');
$ad->date = $request->input('date');
$ad->user_id = auth()->user()->id;
$ad->save();
if ($request->hasFile('photos')) {
$allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
$files = $request->file('photos');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
//$file->move('storage/photos', $filename);
$check = in_array($extension, $allowedfileExtension);
if ($check) {
foreach ($request->photos as $photo) {
$photo->move('storage/photos', $filename);
$img = new AdsPhoto;
$img->ad_id = $ad->id;
$img->filename = $filename;
$img->save();
}
return redirect('/home')->with('success', 'ad + image created');
} else {
echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
}
return redirect('/home')->with('success','ad created');
}
Thank you in advance!
1st mistake, you did looping twice
2nd mistake (you might not realize this) you didnt merge the filename and extension, this will cause an issue when you retrieving the image in blade
therefore correction on your code plus comment to explain it
if ($request->hasFile('photos')) {
$allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
$files = $request->file('photos');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
//$file->move('storage/photos', $filename);
$check = in_array($extension, $allowedfileExtension);
$fullpath = $filename . '.' . $extension ; // adding full path
if ($check) {
// removing 2nd loop
$file->move('storage/photos', $fullpath); // you should include extension here for retrieving in blade later
$img = new AdsPhoto;
$img->ad_id = $ad->id;
$img->filename = $filename;
$img->save();
}
} else {
echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
return redirect('/home')->with('success', 'ad + image created');
}
From the documentation, if you want to put your file on storage instead of on public folder you need to put these few lines of code as below in the your controller class
<?php
...
use Illuminate\Support\Facades\Storage;
...
class YourController extends Controller{
...
// Automatically generate a unique ID for file name...
Storage::putFile('photos', new File('/path/to/photo'));
...
}
This command will put your file into storage folder
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 would like to allow the audio,doc and video file type in uploading file. My question is, how should I allow the audio,doc and video through file upload? In my code the file that allows are :png,gif,jpeg,txt,pdf,docx. This is my code
My controller
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Validator;
use Redirect;
use Request;
use Session;
use App\Administrator;
class ApplyController extends Controller
{
public function multipleUpload()
{
return view('multiple_upload');
}
public function multipleUploadPost() {
// getting all of the post data
$files = Input::file('images');
// Making counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach($files as $file) {
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,docx'
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'uploads';
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension() ;
if($extension == "jpg" || $extension == "PNG" )
{
$destinationPath = 'uploads/image';
}
else if ($extension == "docx" || $extension == "doc")
{
$destinationPath = 'uploads/documents';
}
else if ($extension == "pdf")
{
$destinationPath = 'uploads/pdf';
}
else if ($extension == "xls")
{
$destinationPath = 'uploads/excel';
}
$changeFileName = str_random(40).'.'.$extension;
$upload_success = $file->move($destinationPath, $changeFileName);
$uploadcount ++;
Administrator::create([ // Administrator is the name of my model
'original_filename' => $filename, // Insert the image to the database in column "image"
'change_filename' => $changeFileName // Insert the image to the database in column "image"
]);
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('multiple-upload');
}
else {
Session::flash('alert', 'Upload failed');
return Redirect::to('multiple-upload')->withInput()->withErrors($validator);
}
}
}
My view
<div class="text-content">
<div class="span7 offset1">
#if(Session::has('success'))
<div class="alert-box success">
<h2>{!! Session::get('success') !!}</h2>
</div>
#endif
<div class="secure">Upload form</div>
{!! Form::open(array('url'=>'apply/multiple_upload','method'=>'POST', 'files'=>true)) !!}
<div class="control-group">
<div class="controls">
{!! Form::file('images[]', array('multiple'=>true)) !!}
<p class="errors">{!!$errors->first('images')!!}</p>
#if(Session::has('error'))
<p class="errors">{!! Session::get('error') !!}</p>
#endif
</div>
</div>
{!! Form::submit('Submit', array('class'=>'send-btn')) !!}
{!! Form::close() !!}
</div>
use Mime validation which will allow only those format which you specify
for ex:
foreach ($files as $file){
$validator = Validator::make(
array(
'file' => $file,
'extension' => strtolower($file->getClientOriginalExtension()),
),
[
'file' => 'required|max:100000',
'extension' => 'required|in:mp3,mp4,doc',
],[
'file.required' => 'File is Required',
'extension.in' => ' File Should be of type mp3,mp4 or doc'
]
);
if($validator->fails()){
return response()->json(['status' => 'fail', 'data' => null, 'msg' => $validator->errors()], 200);
}
else{
dd("success");
}
}
List of mime types Available
http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
Hope this might help you