I am trying to upload an image from my react native project using laravel as my backend framework.
This is the data I send :
I receive a warning that my network request failed.
Here is my backend code :
public function upload(Request $request)
{
$image = $request->get('data');
$name = 'Sup';
Image::make($request->get('data'))->save(public_path('images/').$name);
$fileupload = new Fileupload();
$fileupload->filename=$name;
$fileupload->save();
return response()->json(['message' => 'Success']);
}
I have a function, you can try it!
Please change the path before doing anything else (this is the code used to upload one - multiple files at once)
public function uploadImage (Request $request) {
$files = $request->file('images');
$fileText = '';
foreach($files as $file) {
$rules = array('file' => 'required|mimes:png,gif,jpeg');
$validator = Validator::make(array('file' => $file), $rules);
if($validator->passes()){
$destinationPath = 'storage/images/';
$filename = $file->getClientOriginalName();
$unique_name = md5($filename. time()).$filename;
$upload_success = $file->move($destinationPath, $unique_name);
$fileText .= url('storage/images/' . $unique_name) . '|';
}
}
return rtrim($fileText, '|');
}
Related
I'm new to Laravel and using Laravel 6.0. While uploading image I am getting error of SplFileInfo::getSize(): stat failed for C:\xamp\tmp\php14F3.tmp
I searched for solution on google yet couldn't find any solution.
This is my controller function
public function store(PostsCreateRequest $request)
{
//
$input = $request->all();
$user = Auth::user();
if ($request->hasfile('photo_id')) {
$file = $request->file('photo_id');
$name = time() .$size. $file->getClientOriginalName();
$file->move('posts' , $name);
$photo = Photo::create(['path'=>$name]);
$input['photo_id'] = $photo->id;
}
$user->posts()->create($input);
Session::flash('created_post',"The Post has been created");
return redirect('/home');
}
My solution is
use Illuminate\Http\Request; this request instead of old request.
public function saveimage(Request $request){
request()->validate([
'file' => 'required|mimes:jpeg,jpg|max:2048',
]);
if ($files = $request->file('file')) {
$destinationPath = 'public/images/'; // upload path
$profilefile = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profilefile);
$insert['file'] = "$profilefile";
}
$check = Document::insertGetId($insert);
return Redirect::to("home")
->withSuccess('Great! file has been successfully uploaded.');
}
}
Its working fine.
Give the size of the image while giving the validation. The below code is working fine.
public function saveImage(Request $request){
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'image' => 'required|image|mimes:jpeg,jpg,gif,png,svg|max:2048'
]);
$instrument = new \App\Models\Instrument;
$instrument->name = $request->input('name');
$instrument->description = $request->input('description');
$imgfile = $request->file('image');
$instrument->image = $imgfile->getClientOriginalName();
if ($imgfile !== null) {
$filenameWithExt = $imgfile->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $imgfile->getClientOriginalExtension();
$fileNameToStore= $filename.'_'.time().'.'.$extension;
$imgfile->storeAs('public/images', $fileNameToStore);
} else {
//dd("Image Not Uploaded");
}
$instrument->save();
return redirect('/instruments')->with('success', 'Details are uploaded successfully');
}
When I'm storing an image into a database, then it doesn't upload with base URL. How can resolve this type of problem in Laravel?
public function uploadimage(Request $request)
{
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His') . '-' . $filename;
$file->move(public_path('img'), $picture);
$employee_image = Image::create($request->all());
$employee_image->image = $filename;
$employee_image->save();
return response()->json(['message' => 'Image Uploaded Successfully']);
}
return response()->json(['message' => 'Select image first.']);
}
The public_path() function does not intend to be use to serve browser friendly uri, so, you should use \Illuminate\Support\Facades\URL facade instead.
e.g.:
$employee_image->image = URL::asset('storage/employees/').$filename;
$employee_image->save();
Source: Laravel.IO
Try this ....
public function uploadimage(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$employees = new Image($request->input()) ;
if($file = $request->hasFile('image')) {
$file = $request->file('image') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$employees->image = '/public/images/'.$fileName ;
}
$employees->save() ;
return response()->json(['message' => 'Image Uploaded Successfully']);
}
I want to edit the the blog form in Laravel. All other text information like Title, Body are successfully edited. But Image could not be updated. New image is not uploaded and image path is set as C:\xampp\tmp\php2030.tmp.
My Controller for edit.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$post->update($requestData);
if ($request->hasFile('image'))
{
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
$image = '/images/'.$fileNameToStore;
$post->save();
}
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
What is wrong with it?
When PHP receives a file upload, by default it writes it to a temporary directory like you're getting, and automatically deletes the file after the request has been handled.
What you need to do is move the uploaded file to a safe location.
Laravel 5.5 has a store method for file uploads that might be of interest.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
if ($request->hasFile('image')) {
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
// UPDATE TEMPORARY IMAGE PATH WITH ACTUAL PATH
$requestData['image'] = "/media/{$fileNameToStore}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
Please, use the code below:
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$pathToStore = public_path('media');
if ($request->hasFile('image'))
{
$file = $request->file('image');
$rules = array('file' => 'required|mimes:png,gif,jpeg'); // 'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = \Illuminate\Support\Facades\Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
$filename = $file->getClientOriginalName();
$extension = $file -> getClientOriginalExtension();
$picture = sha1($filename . time()) . '.' . $extension;
$upload_success = $file->move($pathToStore, $picture);
if($upload_success)
{
//if success, create thumb
$image = Image::make(sprintf($pathToStore.'/%s', $picture))->resize(600, 531)->save($pathToStore.'/thumb/'.$picture);
}
}
$requestData['image'] = "$pathToStore/{$picture}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
I installed the patch "intervention/image", "must-master" in order to make my image to reduce the size of it to 300 by 300.
I've done some forms and appears to me always the same mistake.
Call to a member function resize() on string
which got the error?
Controller
public function updateProfile() {
$file = Input::file('imagem');
$profileData = Input::except('_token');
$validation = Validator::make($profileData, User::$profileData);
if ($validation->passes()) {
if ($file == null) {
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return view('backend/perfil.index');
}
$file = array_get($profileData,'imagem');
$destinationPath = 'imagens/perfil';
$extension = $file->getClientOriginalExtension();
$filename = rand(11111, 99999) . '.' . $extension;
$reduzir = $filename -> resize (300,300);
$profileData['imagem'] = $filename;
$upload_success = $file->move($destinationPath, $filename);
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil');
} else {
return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
}
}
The issue might be because of these reasons
Have you added this aliases in your app.php
'aliases' => [
//add these three at the bottom
'Form' => Illuminate\Html\FormFacade::class,
'HTML' => Illuminate\Html\HtmlFacade::class,
'Image' => Intervention\Image\Facades\Image::class
],
I believe that you already have form and html helper.
And use this function in the Controller
i.e., just pass the image and size value as the Parameter to this function
In the controller you have just call the below function like
$resizedImage = $this->resize($image, $request->get('image_size'));
And the resize() function was given below
private function resize($image, $size)
{
try
{
$extension = $image->getClientOriginalExtension();
$imageRealPath = $image->getRealPath();
$thumbName = 'thumb_'. $image->getClientOriginalName();
//$imageManager = new ImageManager(); // use this if you don't want facade style code
//$img = $imageManager->make($imageRealPath);
$img = Image::make($imageRealPath); // use this if you want facade style code
$img->resize(intval($size), null, function($constraint) {
$constraint->aspectRatio();
});
return $img->save(public_path('images'). '/'. $thumbName);
}
catch(Exception $e)
{
return false;
}
I'm trying to upload images into a Laravel app that will then need to be publicly displayed. However, I seem to only be able to upload to a folder within the application root. Any attempt to upload to the public directory throws the following error:
protected function getTargetFile($directory, $name = null)
{
if (!is_dir($directory)) {
if (false === #mkdir($directory, 0777, true)) {
throw new FileException(sprintf('Unable to create the "%s" directory', $directory));
I'm assuming this means that Laravel is going to prevent me from uploading to any file that is publicly accessible. I actually rather like this, however, how can I link to images that are outside of the public directory I've tried to ../ my way out of the public folder, but appropriately, that didn't work.
Alternately, anything that will let me uploaded directly to the public folder would be great too.
If it helps, here is my controller method that puts the file in public folder:
$thumbnail_file = Input::file('thumbnail');
$destinationPath = '/uploads/'. str_random(8);
$thumbnail_filename = $thumbnail_file->getClientOriginalName();
$uploadSuccess = Input::file('thumbnail_url')->move($destinationPath, $thumbnail_filename);
Route::post('upload', function(){
$avarta = Input::file('avatar');
if(strpos($avarta->getClientMimeType(),'image') !== FALSE){
$upload_folder = '/assets/uploads/';
$file_name = str_random(). '.' . $avarta->getClientOriginalExtension();
$avarta->move(public_path() . $upload_folder, $file_name);
echo URL::asset($upload_folder . $file_name); // get upload file url
return Response::make('Success', 200);
}else{
return Response::make('Avatar must be image', 400); // bad request
}});
will upload to /public/assets/uploads folder, maybe help you
Your destination path should be:
$destinationPath = public_path(sprintf("\\uploads\\%s\\", str_random(8)));
Try using this one in your controller after creating a folder called uploads in your public and another folder called photos in uploads.
$data = Input::all();
$rules = array(
'photo' => 'between:1,5000|upload:image/gif,image/jpg,image/png,image/jpeg',
);
$messages = array(
'upload' => 'The :attribute must be one of the following types .jpg .gif .png .jpeg',
'between' => 'The :attribute file size must be 1kb - 5mb'
);
$validator = Validator::make($data, $rules, $messages);
if($validator->passes())
{
$uploads = public_path() . '/uploads/photos';
$photo = Input::file('photo');
$photodestinationPath = $uploads;
$photoname = null;
if($photo != null)
{
$photoname = $photo->getClientOriginalName();
Input::file('photo')->move($photodestinationPath, $photoname);
}
$thumbnail = new Model_name();
$thumbnail ->column_name_in_table = $photoname;
and then put this in your routes
Validator::extend('upload', function($attribute,$value, $parameters){
$count = 0;
for($i = 0; $i < count($parameters); $i++)
{
if($value->getMimeType() == $parameters[$i])
{
$count++;
}
}
if($count !=0)
{
return true;
}
return false;});
In the ImageProductController.php (Controller) file insert the following code:
public function store(Request $request, $id)
{
if ($request->hasFile('image')){
$rules = [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg'
];
$this->validate($request, $rules);
// Save file in directory
$file = $request->file('image');
$path = public_path() . '/images';
$fileName = md5(rand(0,9999)).'.'.$file->getClientOriginalExtension();
$file->move($path, $fileName);
$imageProduct = new ImageProduct();
$imageProduct->image = $fileName;
}
In the file create.blade.php (View) insert the following code:
<form enctype="multipart/form-data" method="post" action=" " >
{{ csrf_field() }}
<label for="image" class="btn btn-primary">Inserir Imagem</label>
<input type="file" name="image" id="image" accept="image/*"
class="form-control" value="{{ old('image') }}>
</form>
In the ImageProduct.php file (Model) insert the following code:
public function getUrlAttribute()
{
if(substr($this->image, 0, 4) === "http"){
return $this->image;
}
return '/images/'.$this->image;
}
Good luck!
You need to give permission the laravel folder where you want to store images.
The commend is:
sudo chown www-data:www-data /var/www/html/project-name/path/to/folder.