I have a need to upload multiple images. This code below works well. This is using Intervention Image plugin. I am trying to customise this code to add another field which is a ForeignKey value to the parent of this image model. $request has the value coming from form. How to save it along with images?
The value is:
$request('vehicle_id')
How can tweak the below method so as save includes this vehicle_id as well?
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id)) {
$org_img = File::makeDirectory('images/'.auth()->user()->id, 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if ($org_img == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
}
return redirect('/home')->with('success','Images Uploaded');
}
I found solution
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'vehicle' => 'required'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id.'/')) {
$org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->vehicle = $request->input('vehicle');
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
return redirect('/home')->with('success','Images Uploaded');
Related
While updating the user image unlink image from public folder if exists otherwise do update the user with image. Currently I have no image for user. And while updating user from profile section I am getting this error unlink('images/users') is a directory. I want if image exists for user then unlink the image and upload the new one otherwise just upload the new image.
My controller:
public function changeUserImage(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png|max:10000',
]);
$image = $request->file('image');
if (isset($image)) {
$imageName = time() . '.' . $request->image->getClientOriginalExtension();
if (!file_exists('images/users')) {
mkdir('images/users', 0777, true);
}
if (file_exists('images/users')){
unlink('images/users/' . \auth()->user()->image);
$image->move('images/users', $imageName);
User::find(\auth()->user()->id)->update(['image'=>$imageName]);
}else if (!file_exists('images/users')){
$image->move('images/users', $imageName);
User::find(\auth()->user()->id)->update(['image'=>$imageName]);
}
}
return redirect()->back();
}
Try this. I haven't test it yet. Let me know if you have any questions.
Make sure to Import File: use File;
UPDATED
public function changeUserImage(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png|max:10000',
]);
// Let get the current image
$user = Auth::user();
$currentImage = $user->image;
// Let compare the current Image with the new Image if are not the same
$image = $request->file('image');
// The Image is required which means it will be set, so we don't need to che isset($image)
if ($image != $currentImage) {
// To make our code cleaner let define a directory for DRY code
$filePath = public_path('images/users/');
$imageName = time() . '.' . $request->image->getClientOriginalExtension();
if (!File::isDirectory($filePath)){
File::makeDirectory($filePath, 0777, true, true);
}
$image->move($filePath, $imageName);
// After the Image has been updated then we can delete the old Image if exists
if (file_exists($filePath.$currentImage)){
#unlink($filePath.$currentImage);
}
} else {
$imageName = $currentImage;
}
// SAVE CHANGES TO THE DATA BASE
$user->image = $imageName;
$user->save();
return redirect()->back();
}
To store the image: $request->image->storeAs('images/users/', $file_name);
To delete an image: Storage::delete('images/users/'. $file_name);
The problem:
I want to upload an image to a mySQL database using Laravel.
what I have tried:
I looked for other stack-overflow questions but they weren't helpful.
the result I am expecting :
is to have the image name or path saved to a column in my table on the database , to retrieve and display it later as a post in a blog.
First you need the form on your view (don't forget the csrf token):
<form action="/image-upload" method="POST" enctype="multipart/form-data">
#csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
And on your routes file add the route for POST method:
Route::post('image-upload', 'ImageUploadController#imageUploadPost');
Then on your Controller create the function that will validate and move your image to the 'public/images' folder.
public function imageUploadPost()
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->image->getClientOriginalExtension();
request()->image->move(public_path('images'), $imageName);
}
For better solution please read this: Laravel File Storage
Actually with Laravel it only involves a few lines of code. Let's say you have a user that has an avatar which is stored in the database. Here's how you would store and retrieve the avatar from the database:
1. First you'll need to have an avatar column in the users table that can store binary data. Depending on how large you want to allow the avatar image to be, the data type of the column can be one of the following:
BLOB up to 64KB
MEDIUMBLOB up to 16MB
LONGBLOB up to 4GB
2. To store the uploaded image in the database you can do this:
Route::post('user/{id}', function (Request $request, $id) {
// Get the file from the request
$file = $request->file('image');
// Get the contents of the file
$contents = $file->openFile()->fread($file->getSize());
// Store the contents to the database
$user = App\User::find($id);
$user->avatar = $contents;
$user->save();
});
3. To fetch and ouput the avatar you can do the following:
Route::get('user/{id}/avatar', function ($id) {
// Find the user
$user = App\User::find(1);
// Return the image in the response with the correct MIME type
return response()->make($user->avatar, 200, array(
'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar)
));
});
NOTE: Please have this in your mind, MySQL isn't a suitable solution to store BLOB. You may need to use an object storage service like Amazon S3.
Use this to upload image
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// $this->validate($request,[//'movie_name'=>'required',
// // 'description'=>'required',
// //'video_url'=>'required',
// 'image'=>'required|mimes:jpeg,jpg,png,gif|required|max:10000',
// ]);
if ($request->hasFile('image') && $request->hasFile('image2')) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
else
{
if ( $request->hasFile('image2')) {
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
//echo $destinationPath;exit();
//echo $bg_images;
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
if ($request->hasFile('image') ) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
//'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
// print_r($insert_data);exit();
}
if ( ! $request->hasFile('image2') && ! $request->hasFile('image') ) {
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
// 'bg_images'=>$bg_images,
'updated_at'=>now()
);
// print_r($update_data);exit();
}
}
//exit();
// echo $image;
//exit();
//print_r($insert_data);exit();
$insert=DB::table('movies')->insert($insert_data);
if ($insert) {
return redirect()->route('admin.list_movies')->withSuccess('Record saved');
}
else {
return redirect()->route('admin.list_movies')->withError('Record not saved');
}
}
recently i'm trying to practice with laravel 5.5 and create simple upload and update image
here is my controller on store
$input = $request->all();
$this->validate($request, [
'photo' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:500',
]);
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$photo_name = date('YmdHis'). ".$ext";
$photoName = time().'.'.$request->photo->getClientOriginalExtension();
$request->photo->move(public_path('photo-upload'), $photoName);
$upload_path = public_path('photo-upload');
$input['photo'] = $photoName;
}
}
controller update
if ($request->hasFile('photo')) {
// delete the old/previous one
$exist = Storage::disk('photo')->exists($student->photo);
if (isset($student->photo) && $exist) {
$delete = Storage::disk('photo')->delete($siswa->photo);
}
// upload new one
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
$photoName = time().'.'.$request->foto->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$upload_path = 'photo-upload';
$request->file('photo')->move($upload_path, $phptpName);
$input['photo'] = $iphotoName;
}
}
the store method works perfectly, it uploaded image to the right folder then update the databse
the problem is on the update, it update the database but it didn't upload the image to the photo-upload folder
Any suggestion?
Thanks
I am trying to store an image in cakephp 3.0. I am only able to save the filename in db, however, unable to store the actual file on the server. Need help
Form:
echo $this->Form->create('User', array('url' => array('action' => 'create'), 'enctype' => 'multipart/form-data'));
echo $this->Form->input('upload', array('type' => 'file'));
Images controller:
*/
public function add()
{
$image = $this->Images->newEntity();
//Check if image has been uploaded
if(!empty($this->request->data['Images']['upload']['name']))
{
$file = $this->request->data['Images']['upload']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img' . $file['name']);
//prepare the filename for database entry
$this->data['Images']['image'] = $file['name'];
}
}
if ($this->request->is('post')) {
$image = $this->Images->patchEntity($image, $this->request->data);
if ($this->Images->save($image)) {
$this->Flash->success('The image has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The image could not be saved. Please, try again.');
}
}
$this->set(compact('image'));
$this->set('_serialize', ['image']);
}
For those who are looking for the answer just modify this line :
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img' .DS. $file['name']);
DS is a Directory Separator.
Welcome on stackoverflow!
Please check this question:
cakePHP 3.0 uploading images
This will help you, it's a good plugin for uploading images:
http://cakemanager.org/docs/utils/1.0/behaviors/uploadable/
I have a image decode by base64_decode.
I have a entity Image. This is entity consist : id and path to the file. File of image load to server by this guide http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html.
How encode this string and upload file to server and upload path to database in controller.
my controller
public function updateattachmentAction()
{
$em = $this->getDoctrine()->getManager();
$photo = $em->getRepository('MyPluginBundle:Photo')->findOneById(4);
$str="";
$request = $this->container->get('request');
$image = $request->query->get('image');
// file_put_contents($photo, base64_decode($data));
// $photo->upload();
// $em->persist($photo);
// $em->flush();
$response = array("code" => 100,"success" => true);
//you can return result as JSON
return new Response(json_encode($response));
}
it should help DataUriNormalizer
https://symfony.com/blog/new-in-symfony-3-1-data-uri-normalizer## Heading ##
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;
$normalizer = new DataUriNormalizer();
$avatar = $normalizer->denormalize('data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=', 'SplFileObject');
// $avatar is a SplFileObject with the GIF image contents
and this https://github.com/hshn/base64-encoded-file
use Hshn\Base64EncodedFile\HttpFoundation\File\Base64EncodedFile;
$file = new Base64EncodedFile(base64_encode($data));
$file->getPathname(); // "/path/to/file"
$file instanceof Symfony\Component\HttpFoundation\File\File; // true