Problem uploading images with Axios and Laravel - laravel

I'm trying to upload and save images with Axios and a Laravel API, but i'm getting a 422 error.
I've tested with Postman and i have the same result, i have a similar controller**(without the Foreach)** but to upload only one image at once and it works fine.
///Axios
async submitFiles(){
let fd = new FormData()
for(var i = 0; i < this.files.length; i++){
let file = this.files[i]
fd.append('photo[' + i + ']', file)
}
try{
await this.$axios.$post(`/albums/${this.$route.params.id}/photos`, fd, {headers:{'Content-Type': 'multipart/form-data'}})
console.log(...fd)
alert('uploaded')
this.files = []
}
catch(err){
console.log(err)
alert(err)
}
}
//Laravel
class PhotosInAlbumController extends Controller
{
public function store(PhotoInAlbumRequest $request, Album $album)
{
if($request->hasfile('photo'))
{
$photo = new PhotoInAlbum();
$photo->photo = $request->photo;
$images[] = $request->file('photo');
foreach ($images as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathInfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$filenameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('photo/images', $filenameToStore,'public');
$photo->photo = $path;
$album->photos()->save($photo);
}
}
return $photo;
}
}
Hope someone can help me to figure out what's going on.
Thanks in advance (=

First, sorry I can't comment yet. But I see in this line:
$images[] = $request->file('photo');
that a bi-dimensional array is built. I would try the assignment without the brackets:
$images = $request->file('photo');

Related

Save both original image and conversion to webp in laravel storage

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:

upload multiple image in flutter app to a laravel api

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.

my image are not saved in upload folder in laravel

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();

Error Call to a member function getRealPath() on bool

I am get this error"Call to a member function getRealPath() on bool"
if($request->hasFile('content')) {
$filenameWithExt = $request->file('content')->getClientOriginalName();
$filename = pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension = $request->file('content')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('content')->storeAs('public/content',$fileNameToStore);
} else {
$fileNameToStore = 'No Image,Music and Video selected please! check and try again.';
}
$post = new Post;
$post->body = $request->input('body');
$post->content = $fileNameToStore;
//Error exist here
$post = Image::make($fileNameToStore->getRealPath());
$post->text('The quick brown fox jumps over the lazy dog.');
$post->save();
getRealPath() is the method of SplFileInfo
See: https://www.php.net/manual/en/splfileinfo.getrealpath.php
If u want to use getRealPath(), try this:
Image::make(
$request->file('content')->getRealPath()
)->save('public/content',$fileNameToStore);

Cannot upload an image to S3 Bucket

I am trying to upload an image to Amazon s3 bucket using vue js and laravel. But when i upload it the following exception appears :-
here's what i wrote in my controller to upload the file.
public function addProperty(Request $request)
{
$property = new Property;
$property->title = request('title');
$property->property_type = request('type');
$property->property_sub_type = request('subtype');
$property->address = request('address');
$property->property_index = 400;
#$property->save();
if ($request->hasFile('image')) {
$fileNameWithExtension = $request->file('image')- >getClientOriginalName();
$fileName = pathinfo($fileNameWithExtension, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore =$fileName.'_'.time().'_'.'.'.$extension;
$disk = Storage::disk('s3');
$disk->put($fileNameStore, fopen($request->file('image'), 'r+'), 'public');
$profilePicImageUri = Storage::disk('s3')->url($fileNameStore);
dd($profilePicImageUri);
return $profilePicImageUri;
}
}
here's what i have done in Vue
onSubmit(){
let self = this;
let data = new FormData();
data.append('image',this.file);
data.append('title',this.propertyTitle);
data.append('type',this.type);
data.append('subtype',this.subtype);
data.append('lat',this.lat);
data.append('long',this.long);
data.append('address',this.address);
let config = {
headers:{
'Content-Type' : 'multipart/form-data'
}
}
axios.post(baseUrl + "api/admin/addproperty",data,config)
.then(function (response) {
console.log(response);
}).catch(function (error) {
{
console.log(error);
}
})
},
I have already setup my aws Configuration in env file. Here's my configuration
AWS_ACCESS_KEY_ID=XXXX
AWS_SECRET_ACCESS_KEY=XXX
AWS_DEFAULT_REGION=eu-central-1
AWS_BUCKET= php-laravel-upload
AWS_URL = https://php-laravel-upload.s3.eu-central-1.amazonaws.com
I don't understand what i am doing wrong. Can anyone help me?
try like that
if ($request->hasFile('image')) {
$fileInstance = $request->file('image');
$fileNameStore = $fileInstance->getClientOriginalName().'_'.time().'_.'.$fileInstance->getClientOriginalExtension();
Storage::disk('s3')->put($fileNameStore, $fileInstance, 'public');
$profilePicImageUri = Storage::disk('s3')->url($fileNameStore);
// dd($profilePicImageUri);
return $profilePicImageUri;
}

Resources