upload multiple image in flutter app to a laravel api - laravel

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.

Related

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

How to organize data to send a post request to a API? laravel + vue-cli project

i'm writing a code using laravel as backend and vue-cli as frontend.
i've got a problem with the data to send to an API laravel restful controller. I get back as answer the err 500.
That's my saveEvent code:
saveEvent() {
const staff = this.$store.getters.get_selected_staff.map(
raw_staff => {
return {
...raw_staff,
icon: "mdi-drama-masks" ? "actor" : "technician",
percent:
raw_staff.percent == "full"
? 1
: eval(raw_staff.percent),
allowance: parseInt(raw_staff.allowance),
daily: parseInt(raw_staff.daily)
};
}
);
const show = {
...this.$store.getters.get_tournee_show_detail
};
this.$http
.post(
"http://localhost:8080/api/tourneeDetail",
`show=${JSON.stringify(show)}&staff=${JSON.stringify(
staff
)}`
)
.then(response => {
this.closeEvent();
})
.catch(error => {
console.log("errore nella registrazione", error);
});
// );
}
The datas goest straight to the controller and get manages in this way:
public function store(Request $request)
{
//
dd($request->all());
$tournee = new TourneeDetail;
$show = json_decode($request->show, true);
$staff = json_decode($request->staff, true);
foreach ($show as $detail => $value){
if($detail == "stage_id"){
$tournee->stage_id = $value['id'];
}
else{
$tournee[$detail] = $value;
}
}
$tournee->save();
foreach ($staff as $row){
$staff = new Staff;
foreach ($row as $detail => $value){
if ($detail!="icon" && $detail!="names" ){
$staff[$detail] = $value;
}
}
$staff->type = $row["icon"];
$staff->tournee_detail_id = $tournee->id;
$staff->save();
foreach ($row["names"] as $id){
$staff_person = new StaffPerson;
$staff_person->person_id = $id;
$staff_person->staff_id = $staff->id;
$staff_person->save();
}
}
return $tournee;
}
The problem is that i get the 500 error on the 1rst foreach. I put a dd to check the $request->all() and i noticed that the payload sent is correct but the preview is an empty array!
I dunno how to fix this problem..any help would be appreciated!
Thank you
Valerio

Correctly upload an image to database. Laravel vue.js

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!

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;
}

Problem uploading images with Axios and 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');

Resources