I'm having problem with this code in update photo:
I already have function on it but it doesnt work
if (isset($request['image'])) {
$image = request()->file('image')->move("pictures/{$users[0]['username']}", 'public');
}
if (isset($request['licenseimage_front'])) {
$request['licenseimage_front'] = request()->file('licenseimage_front')->store("licensepicture/front/{$users[0]['username']}", 'public');
}
if (isset($request['licenseimage_back'])) {
$request['licenseimage_back'] = request()->file('licenseimage_back')->store("licensepicture/back/{$users[0]['username']}", 'public');
}
Related
I'm trying to save original jpg image and also a converted webp image to my storage when I'm storing images in my project.
public function store($data)
{
if (!$data->hasFile('fileName')) {
return response()->json(['upload_file_not_found'], 400);
}
$allowedfileExtension = ['jpg', 'jpeg'];
$files = $data->file('fileName');
$errors = [];
$images = [];
foreach ($data->fileName as $mediaFiles) {
$extension = $mediaFiles->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
// $path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
//store image file into directory and db
$image = new Image();
$image->title = $name;
// $image->path = substr($path, 7);
$image->description = $data->description;
$image->author_id = $data->author_id;
$image->save();
//put image to storage wih unique folder
$path = $mediaFiles->storeAs('public/images/article-images/'.$image->id, $name);
//try to convert to webp and add to storage
$image = InterventionImage::make($mediaFiles)->encode('webp', 90)->resize(200, 250)->save('public/images/' . $name . '.webp');
//
//update images path in database
$image->update(['path' => substr($path, 7)]);
//add to attach the article id
if ($data->article_id) {
$image->articles()->attach($data->article_id);
}
array_push($images, $image);
} else {
return response()->json(['invalid_file_format'], 422);
}
}
return $images;
}
I'm using intervention library but when I try to save converted image to my storage I get the error "message": "Can't write image data to path (public/images/newimage.jpg.webp)",
can someone help with this or have any other suggestion how to do this?
if you want to convert image in to WEBP without any service or package, try this method. work for me. have any question can ask. Thankyou
$post = $request->all();
$file = #$post['file'];
$code = 200;
$extension = $file->getClientOriginalExtension();
$imageName = $file->getClientOriginalName();
$path = 'your_path';
if(!$file->move(public_path($path), $imageName)){
$code = 404;
}
if(in_array($extension,["jpeg","jpg","png"])){
//old image
$webp = public_path().'/'.$path.'/'.$imageName;
$im = imagecreatefromstring(file_get_contents($webp));
imagepalettetotruecolor($im);
// have exact value with WEBP extension
$new_webp = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp', $webp);
// set qualityy according to requirement
return imagewebp($im, $new_webp, 50);
}
this will save JPG/PNG and WEBP file both to the move Folder.
If someone ever have the same problem I did it like this
public function newStore($data)
{
if (!$data->hasFile('fileName')) {
return response()->json(['upload_file_not_found'], 400);
}
$allowedfileExtension = ['jpg', 'jpeg'];
$files = $data->file('fileName');
$errors = [];
$images = [];
foreach ($data->fileName as $mediaFiles) {
$extension = $mediaFiles->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
// $path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
//getting the name of the file without extension
$filename = pathinfo($name, PATHINFO_FILENAME);
//store image file into directory and db
$image = new Image();
$image->title = $name;
// $image->path = substr($path, 7);
$image->description = $data->description;
$image->author_id = $data->author_id;
$image->save();
//put image to storage in unique folder
$path = $mediaFiles->storeAs('public/images/article-images/' . $image->id, $name);
//imege conversion in webp format and move to right folder
$interventionImage = InterventionImage::make($mediaFiles)->stream("webp", 100);
Storage::disk('local')->put($filename . '.webp', $interventionImage, 'public');
Storage::move($filename . '.webp', 'public/images/article-images/' . $image->id . '/' . $filename . '.webp');
//update images path in database
$image->update(['path' => substr($path, 7)]);
//add to attach the article id
if ($data->article_id) {
$image->articles()->attach($data->article_id);
}
array_push($images, $image);
} else {
return response()->json(['invalid_file_format'], 422);
}
}
return $images;
}
and my folder structure looks like this:
Here is my function in flutter
I have use multi_image_picker to pick images sand i have save them in that variable images. Now I want post those images in laravel api. But this don't work.
if(images != null ){
try{
List<MultipartFile> allMultiFiles = [];
for (Asset asset in images) {
ByteData byteData = await asset.getByteData();
List<int> imageData = byteData.buffer.asUint8List();
print(imageData);
var multipartFile = new MultipartFile.fromBytes(
imageData,
filename: asset.name,
);
allMultiFiles.add(multipartFile);
}
FormData formData = FormData.fromMap({
'images' : allMultiFiles
});
var response = await dio.post(UPLOAD_URL, data:formData);
if(response.statusCode == 200){
print('done');
}else{
print('not save image. Error !!');
}
}catch (e){
print(e.toString());
}
}
}
Here is my function to store
public function save(Request $request){
if(!$request->hasFile('images')){
return response()->json([
'upload file not found' => 'not found'
],400);
}else{
$allowedExtension = ['jpg','jpeg','png'];
$files = $request->file('images');
$erros = [];
foreach ($files as $file){
$extension = $file->getClientOriginalExtension();
$check = in_array($extension,$allowedExtension);
if($check) {
foreach($request->images as $mediaFiles) {
$path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
return response()->json([
'message' => 'images saved'
],200);
}
} else {
return response()->json(['invalid_file_format'], 422);
}
}
}
}
It not work, images are not saved.
I'm beginner in flutter and thanks for your help.
whenever I uploaded an image in laravel, the image is upload to the database but after database uploading, my image didn't save that image in my root folder,
here is my upload code:
public function store(Request $request)
{
$records = $request->all();
if ($records != '') {
if ($request->session()->has('is_user_logged')) {
$UserPostModel = new UserPostModel;
$UserPostModel->uid = $request->session()->get('uid');
$UserPostModel->uname = $request->session()->get('name');
$UserPostModel->msg = $request->input('status');
$UserPostModel->eid = $request->input('event');
if ($request->hasFile('image')) {
if ($request->file('image')->isValid()) {
$fileName = $request->file('image')->getClientOriginalName();
$fileName = time() . "_" . $fileName;
$request->file = move_uploaded_file('uploads',$fileName);
$UserPostModel->image = $fileName;
}
}
$UserPostModel->save();
return redirect('uprofile')->with('message', 'Seccessfully Post !');
} else {
return redirect('login');
}
} else {
return redirect('/uprofile')->with('message', 'Please select image!');
}
}
Use store method and pass the driver as the second argument
$path = $request->file('image')->store($store_path, 'public');
Please replace this code with your image upload condition.
if ($file = $request->file('image')) {
$name = time() . $file->getClientOriginalName();
$file->move('uploads', $name);
$UserPostModel->image = $name;
}
$UserPostModel -> save();
I'm trying to upload an image to the database but no matter what I try I either get this error
Call to a member function getClientOriginalExtension() on null
or it says it saved correctly but it doesn't save anything
The following code is in the vue.js file in the submit function for the form where this the image is being uploaded. This is what I've tried to send the file to the controller
This gives me the error above
if (this.form.file && this.form.imageUrl) {
this.form.file = this.form.imageUrl;
} else {
}
var data = Converter.objectToFormData(this.form);
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
//send code
} else {
//send updated
}
}
This also gives me the error above
let data = Object.assign({}, this.form);
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
//send code
} else {
//send updated
}
}
This doesn't give me any errors, but nothing gets saved
var data = new FormData();
data.append('question', this.form.question);
data.append('instruction', this.form.instruction);
data.append('survey_section_id', this.form.survey_section_id);
data.append('response_type_id', this.form.response_type_id);
data.append('questionOptions', this.form.questionOptions);
data.append('rank', this.form.rank);
data.append('num', this.form.num);
data.append('show_text', this.form.show_text);
data.append('file', this.form.file);
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
//send code
} else {
//send updated
}
}
This is the code in the controller where the error gets triggered
$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
$imageFile = $request->file('file');
$filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
$imageFile->move($destino, $filename);
$preg->image = $destino . '/' . $filename;
}
if I dd($imageFile) it always returns null or false, my guess is that the file isn't being sent as a file but I'm not sure what I'm doing wrong or why this is happening, the $image returns true so it does go into that if statement.
Assuming you have put enctype="multipart/form-data" on your form, there was an error in a laravel 6 that forced me to do this before getting the image:
$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
$size = $request->file('file')->getSize();
$imageFile = $request->file('file');
$filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
$imageFile->move($destino, $filename);
$preg->image = $destino . '/' . $filename;
}
I'm not sure if it gave me the same error, but the file was always null if you didn't get the size before,
Hope it helps!
I made a method that handles image. The problem is I want to call that method in my Edit method few times because there are 3 buttons for uploading image. But after calling my method for IMAGE the EDIT method just stops after first image. How can I stop that?
if($request->has('picture1')) {
return $this->upload_image($company, $asset, $request->picture1);
}
if($request->has('picture2')) {
return $this->upload_image($company, $asset, $request->picture2);
}
if($request->has('picture3')) {
return $this->upload_image($company, $asset, $request->picture2);
}
And this is my function for uploading image
public function upload_image($company, $asset, $image)
{
$filename = uniqid(rand());
$image = str_replace('data:image/png;base64,', '', $image);
$image = str_replace(' ', '+', $image);
if (!file_exists(public_path('/uploads/assets/pictures/' . $company->id . '/'))) {
File::makeDirectory(public_path('/uploads/assets/pictures/' . $company->id . '/'), 0777, true);
}
Image::make($image)->resize(1024, null, function ($constraint) { $constraint->aspectRatio();})
->save( public_path('/uploads/assets/pictures/' . $company->id . '/'. $filename ) );
}
How can i go back to my function after handling first image?
You have to simply remove the return keyword like this :
if($request->has('picture1')) {
$this->upload_image($company, $asset, $request->picture1);
}
if($request->has('picture2')) {
$this->upload_image($company, $asset, $request->picture2);
}
if($request->has('picture3')) {
$this->upload_image($company, $asset, $request->picture2);
}