Unable to upload a file using Vue.js to Lumen backend? - laravel

I have tried to upload a file using vue.js as front end technology and laravel in the back end. I have tried to pass the file object using formData javascript object but the server responds as the value is not passed.
I have tried to log the file using console.log and it appropriately displays the data.
Consider that I have discarded some field names.
Template Code
<template>
<b-container>
<div align="center">
<b-card class="mt-4 mb-4 col-md-8" align="left" style="padding: 0 0;">
<card-header slot="header" />
<b-form>
<div class="row">
<div class="col-6 col-md-6">
<b-button
type="submit"
variant="success"
class="float-right col-md-5"
v-if="!update"
#click="save"
squared
>
<i class="fas fa-save"></i>
Save
</b-button>
</div>
</div>
<hr style="margin-top: 10px;" />
<b-form-group
label-cols="12"
label-cols-lg="3"
label-for="input-2"
label="Remark: "
label-align-sm="right"
label-align="left"
>
<b-form-textarea
id="textarea"
v-model="record.remark"
rows="2"
max-rows="3"
></b-form-textarea>
</b-form-group>
<b-form-group
label-cols="12"
label-cols-lg="3"
label-for="input-2"
label="Remark: "
label-align-sm="right"
label-align="left"
>
<b-form-file
v-model="record.attachement"
:state="Boolean(record.attachement)"
placeholder="Choose a file..."
drop-placeholder="Drop file here..."
></b-form-file>
</b-form-group>
</b-form>
<status-message ref="alert" />
</b-card>
</div>
</b-container>
</template>
Script Code
<script>
import { mapGetters, mapActions } from "vuex";
export default {
props: ["id", "user_id"],
data: () => ({
record: {
remark: "",
attachement: null
}
}),
methods: {
...mapActions([
"addBenefitRequest",
]),
save(evt) {
evt.preventDefault();
this.$validator.validate().then(valid => {
if (valid) {
const Attachement = new FormData();
Attachement.append("file", this.record.attachement);
var object = {
remark: this.remark
};
this.addBenefitRequest(object, Attachement);
}
});
},
},
computed: mapGetters([
"getStatusMessage",
"getBenefitRequest",
])
};
</script>
Store Code
async addBenefitRequest({ commit }, object, Attachement) {
try {
const response = await axios.post(
commonAPI.BENEFIT_BASE_URL + "/benefit-requests",
object,
Attachement,
{
headers: {
"Content-Type": "multipart/form-data"
}
}
);
commit("pushBenefitRequest", response.data);
commit("setStatusMessage", "Record has been added.");
} catch (error) {
return error
},
Controller Code
public function store(Request $request, Request $request2)
{
$this->validate($request, [
'employee_id' => 'required|string',
'requested_date' => 'required|date',
// 'benefit_type_id' => 'required|string|exists:benefit_types,id',
'reason' => 'required|string',
]);
$this->validate($request2, [
'attachement' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
// $success = BenefitRequest::exists($request->employee_id);
// if(!$success)
// return response()->json("Employee doesn't exist", 422);
$id = (string) Str::uuid();
if($request2->attachement)
{
$attachement = $request2->file('attachement')->store('Benefits');
$request->merge(['attachement' => $attachement]);
}
// $request->attachement = $request->file('attachement')->store('Benefits');
$request->merge(['id' => $id]);
BenefitRequest::create($request->all());
return response()->json('Saved', 201);
}
Route
$router->post('',
['uses' => 'BenefitRequestController#store',
'group'=>'Benefit requests',
'parameter'=>'employee_id, requested_date, requested_by, benefit_type_id, reason, remark, status',
'response'=>'<statusCode, statusMessage>'
]);

Here is an example. you can try it
index.vue
`<div id="app">
<div v-if="!image">
<h2>Select an image</h2>
<input type="file" #change="onFileChange">
</div>
<div v-else>
<img :src="image" />
<button #click="removeImage">Remove image</button>
</div>
</div>`
new Vue({
el: '#app',
data: {
image: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function (e) {
this.image = '';
}
}
})

Related

Axios post request error when sending an array with an image

I have a form that has an array input and an image, when sending the request without the image it's getting stored correctly in the database, when the image input and the "Content-Type": "multipart/form-data" header both added, it send the request with the correct data but it outputs that the array data is invalid.
the code is written in Vue 3 and the backend is a laravel api.
<script>
import axios from "axios";
export default {
name: "AddPayloadModel",
data() {
return {
drone_id: [],
drone_models: [],
image: null,
previewImage: null,
};
},
created() {
this.getDroneModels();
},
methods: {
getDroneModels() {
axios.get("http://127.0.0.1:8000/api/drone-models").then((response) => {
this.drone_models = response.data;
});
},
imgUpload(e) {
this.image = e.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(this.image);
reader.onload = (e) => {
this.previewImage = e.target.result;
};
},
submit(e) {
const form = new FormData(e.target);
const inputs = Object.fromEntries(form.entries());
inputs.drone_id = Object.values(this.drone_id);
console.log(inputs.drone_id);
axios
.post("http://127.0.0.1:8000/api/payload-model/add", inputs, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
if (res.data.isUnattachableDrones) {
console.log(res);
alert(res.data.unattachableDrones);
} else {
this.$router.push("/home");
}
})
.catch((e) => {
console.error(e);
});
},
},
};
</script>
<template>
<main class="form-signin">
<form #submit.prevent="submit">
<h1 class="h3 mb-3 fw-normal">Add Payload Model</h1>
<div class="form-floating">
<input
class="form-control"
autocomplete="off"
name="brand_name"
placeholder="Brand Name"
/>
<label>Brand Name</label>
</div>
<div class="form-floating">
<input
class="form-control"
autocomplete="off"
name="model_name"
placeholder="Model name"
/>
<label>Model Name</label>
</div>
<div class="form-floating">
<input
class="form-control"
autocomplete="off"
name="type"
placeholder="Type"
/>
<label>Type</label>
</div>
<select
v-model="drone_id"
multiple="multiple"
name="drone_id"
style="height: auto"
class="form-select last-input"
>
<template v-for="drone in drone_models">
<option :value="drone.id">
{{ drone.brand_name }}
</option>
</template>
</select>
<input
name="image"
ref="fileInput"
accept="image/*"
type="file"
#input="imgUpload"
/>
<button class="w-100 btn btn-lg btn-form" type="submit">Submit</button>
</form>
</main>
</template>
here is the response when submitting the form.
and here is the payload.
It got solved by changing the way to push data to the post request to a formData and append it manually like this.
submit() {
const formData = new FormData();
formData.append(
"brand_name",
document.getElementById("brand_name").value
);
formData.append(
"model_name",
document.getElementById("model_name").value
);
formData.append("type", document.getElementById("type").value);
formData.append("image", document.getElementById("image").files[0]);
this.drone_id.forEach((drone_id) => {
formData.append("drone_id[]", drone_id);
});
const headers = { "Content-Type": "multipart/form-data" };
axios
.post("http://127.0.0.1:8000/api/payload-model/add", formData, headers)
.then((res) => {
console.log(res);
if (res.data.isUnattachableDrones) {
console.log(res);
alert(res.data.unattachableDrones);
} else {
this.$router.push("/home");
}
})
.catch((e) => {
console.error(e);
});
},

Capturing multiple image in Vue Js

I have a problem capturing multiple images to my function in vue and pass to the controller. I am trying to modify my blade file which works well when using just the normal form. I am trying to modify to vue but I have a problem with image section. Please assist me on how to achieve this.
my form:
<label for="">Description</label>
<textarea name="description" class="form-control" v-model="description"> </textarea>
<label for="">Images</label>
<input type="file" #change="fieldChange" class="form-control input-sm" name="images[]"
multiple>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
The vue section
data(){
return {
id:'',
price:'',
title:'',
description:'',
location:'',
images:[],
}
},
methods:{
fieldChange(e){
let selectedFiles=e.target.files;
if(!selectedFiles.length){
return false;
}
for(let i=0;i<selectedFiles.length;i++){
this.images.push(selectedFiles[i]);// am able to console the images
}
},
saveImageData(){
var self=this;
axios.post('/senddata',{
title:this.title,
description:this.description,
location:this.location,
images:this.images.file.name,
price:this.price,
})
},
My Laravel function
public function store(Request $request)
{
$product=Products::create([
'title'=>$request['title'],
'description'=>$request['description'],
'price'=>$request['price'],
'location'=>$request['location']
]);
$images= $request->file('images');
foreach ($images as $image){
$move=$image->move(public_path().'/images2/',$image->getClientOriginalName());
if($move){
$imagedata=Images::create([
'title'=>$image->getClientOriginalName(),
'filename'=>$image->getClientOriginalName()
]);
$product->images()->attach([$imagedata->id]);
}
Here is the working code for vuejs part - https://picupload.netlify.app/
https://github.com/manojkmishra/dw_take5/blob/master/src/components/ImageUploader.vue
Vue part
<template>
<div class="uploader"
#dragenter="OnDragEnter"
#dragleave="OnDragLeave"
#dragover.prevent
#drop="onDrop"
:class="{ dragging: isDragging }">
<div class="upload-control" v-show="images.length">
<label for="file">Select files</label>
<button #click="upload">Upload</button>
</div>
<div v-show="!images.length">
<i class="fa fa-cloud-upload"></i>
<p>Drag your images here</p><div>OR</div>
<div class="file-input">
<label for="file">Select files</label>
<input type="file" id="file" #change="onInputChange" multiple>
</div>
</div>
<div class="images-preview" v-show="images.length">
<div class="img-wrapper" v-for="(image, index) in images" :key="index">
<img :src="image" :alt="`Image Uplaoder ${index}`">
<div class="details">
<span class="name" v-text="files[index].name"></span>
<span class="size" v-text="getFileSize(files[index].size)"> </span>
</div>
</div>
</div>
<div v-show="images.length" class="progress">
<div
class="progress-bar progress-bar-info progress-bar-striped"
role="progressbar" :aria-valuenow="progress"
aria-valuemin="0" aria-valuemax="100"
:style="{ width: progress + '%' }"
>
{{ progress}}%
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default
{ data: () => ({ isDragging: false, dragCount: 0, files: [],images: [] ,progress:0}),
methods: {
OnDragEnter(e) { e.preventDefault();
this.dragCount++;
this.isDragging = true;
return false;
},
OnDragLeave(e) { e.preventDefault();
this.dragCount--;
if (this.dragCount <= 0) this.isDragging = false;
},
onInputChange(e) { const files = e.target.files;
Array.from(files).forEach(file => this.addImage(file));
},
onDrop(e) {console.log('ondrop-evnt e=',e)
e.preventDefault();
e.stopPropagation();
this.isDragging = false;
const files = e.dataTransfer.files;
Array.from(files).forEach(file => this.addImage(file));
},
addImage(file) {console.log('addimage file=',file)
if (!file.type.match('image.*')) { this.$toastr.e(`${file.name} is not an image`);
return;
}
this.files.push(file);
const img = new Image(),
reader = new FileReader();
reader.onload = (e) => this.images.push(e.target.result);
reader.readAsDataURL(file);
console.log('addimage this.images=',this.images)
},
getFileSize(size) { const fSExt = ['Bytes', 'KB', 'MB', 'GB'];
let i = 0;
while(size > 900) { size /= 1024; i++; }
return `${(Math.round(size * 100) / 100)} ${fSExt[i]}`;
},
upload() { //this.progress = '0';
const formData = new FormData();
this.files.forEach(file =>
{ formData.append('images[]', file, file.name); });
console.log('upload triggered FormData=',formData)
// resp=axios.post('http://127.0.0.1:8000/sendemail1',this.formData);
// axios.post('http://127.0.0.1:8000/api/imagesupload', formData,
axios.post('https://uat.oms.dowell.com.au/api/imagesupload', formData,
{onUploadProgress:uploadEvent=>{ this.progress=Math.round(uploadEvent.loaded/uploadEvent.total*100);
console.log('upld prges:'+ Math.round(uploadEvent.loaded/uploadEvent.total*100)+'%')
}
})
//axios.post('https://uat.oms.dowell.com.au/api/imagesupload', formData)
.then(response => {
this.$toastr.s('All images uplaoded successfully');
this.images = [];
this.files = [];
this.progress = 0;
})
.catch(() => {
this.$toastr.e('Could not upload the files!');
this.images = [];
this.files = [];
this.progress = 0;
});
}
}
}
</script>
Another version with vuetify
https://github.com/manojkmishra/take5-front-admin/blob/master/src/components/img/imgup.vue
Here is laravel part
public function imagesupload(Request $request){
if (count($request->images)) {
foreach ($request->images as $image) {
$image->store('images');
}
}
return response()->json(["message" => "Done"]);
}
Another way in laravel is here
https://github.com/manojkmishra/take5-api/blob/master/app/Http/Controllers/PicController.php

Cannot save multiple Image using Form Data

First of all this is the error that I get.
This is my first time working with Multiple Image with other Inputs.
as you can see in my FormData Headers the picture File is an Empty Array.
But inside the console it returns a file.
my question for this one that is this good? because the picture that I'm sending is a PNG one but it only says FILE.
This is my Vue Code.
<q-dialog
v-model="uploadForm"
transition-show="slide-up"
transition-hide="slide-down"
persistent
>
<q-card style="width: 700px; max-width: 50vw;">
<q-card-section>
<div class="text-h6">Add Product</div>
</q-card-section>
<div class="q-pa-md">
<form
action="http://127.0.0.1:8000/api/createProduct"
class="q-gutter-md"
method="POST"
enctype="multipart/form-data"
>
<q-input outlined label="Product name" v-model="data.productName" />
<q-input
multiple="multiple"
outlined
type="file"
accept="image/png,jpg/jpeg"
#change="onFilePicked"
ref="file"
>
<template v-slot:prepend>
<q-icon name="attach_file" />
</template>
</q-input>
<div>
<div class="image-category">
<div v-for="(image, key) in data.picture" :key="key">
<div class="image-item">
<img
class="grid"
:src="image.src"
width="300"
height="300"
/>
</div>
</div>
</div>
</div>
<q-input outlined label="Description" v-model="data.description" />
<q-input
prefix="₱ "
type="number"
outlined
label="Price"
v-model="data.price"
/>
<q-select
square
outlined
v-model="data.category_id"
:options="categories"
:option-value="'id'"
:option-label="'categoryName'"
label="Category"
/>
<div class="q-ma-md float-right">
<q-btn label="Submit" color="primary" #click="createProduct" />
<q-btn
label="Cancel"
color="primary"
flat
class="q-ml-sm"
#click="closeCreateModal"
/>
</div>
</form>
</div> </q-card
></q-dialog>
My returning Data()
data: {
picture: [],
productName: "Grizzly Bear",
description: "Machaba.",
price: "260000",
category_id: []
},
my #Change in accepting multiple Images.
onFilePicked(e) {
let selectedFiles = e.target.files;
for (let i = 0; i < selectedFiles.length; i++) {
let img = {
src: URL.createObjectURL(selectedFiles[i]),
file: selectedFiles[i]
};
this.data.picture.push(img);
console.log(this.data.picture, "inside");
}
console.log(this.data.picture, "outside");
},
My CreatingProduct method.
createProduct() {
let t = this.data;
if (
t.picture == "" ||
t.productName.trim() == "" ||
t.description.trim() == "" ||
t.price == "" ||
t.categories == ""
) {
this.uploadForm = false;
this.$q
.dialog({
title: "Incomplete Details",
message: "Please fill up all the fields in the Product",
persistent: true,
color: "negative"
})
.onOk(() => {
this.uploadForm = true;
});
} else {
let formData = new FormData();
const picture = JSON.stringify(this.data.picture); // returns [object, object] so I needed to do
//this.
const category_id = JSON.stringify(this.data.category_id);
formData.append("picture", picture);
formData.append("productName", this.data.productName);
formData.append("description", this.data.description);
formData.append("price", this.data.price);
formData.append("category_id", category_id);
let config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
this.$axios
.post("http://127.0.0.1:8000/api/createProduct", formData, config)
.then(response => {
this.products.unshift(response.data);
this.uploadForm = false;
(this.data = ""),
this.$q.notify({
icon: "info",
message: "Product Added Successfully",
color: "positive"
});
})
.catch(() => {
this.$q.notify({
color: "negative",
position: "top",
message: "Unable to save Product",
icon: "report_problem"
});
});
}
}},
my Backend in laravel
public function createProduct(Request $request)
{
$this->validate($request,[
'productName' => 'required',
'description' => 'required',
'picture' => 'required|image|mimes:jpg,png,jpeg|max:2048',
'price' => 'required',
'category_id' => 'required'
]);
$product = new Product($request->input());
if($request->hasFile('picture')){
foreach($request->file('picture') as $file){
$name = $file->getClientOriginalName();
$file->move(public_path().'/uploads/',$name);
$product->picture = $name;
}
}
$product->save();
return response()->json($product);
}
Can anyone explain to me what is wrong? I made my research and it doesn't work. and also how do you edit a multiple Image? How would you select a specific image in the Index to make that one being edit.
this is my first time working with Quasar + Laravel in creating a Product with Multiple Image.
I think you are doing some things wrong, if you use a framework try to use it as it was intended either the validations or components they have, I detail an example
new Vue({
el: '#q-app',
data: function() {
return {
uploadForm: true,
data: {
picture: [],
productName: "Grizzly Bear",
description: "Machaba.",
price: "260000",
category_id: null
},
categories: [
{ id: 1, categoryName: 'categoria 1' }
]
}
},
methods: {
createProduct() {
this.$q.loading.show()
let formData = new FormData()
formData.append("picture", this.data.picture);
formData.append("productName", this.data.productName);
formData.append("description", this.data.description);
formData.append("price", this.data.price);
formData.append("category_id", this.data.category_id.id);
axios.post('http://localhost:8000/', formData, {
'headers': {
'Content-Type': 'multipart/form-data;'
}
}).then((response) => {
alert(response)
}).catch(error => {
if (error) {
console.log('error', error)
}
}).finally(() => {
this.$q.loading.hide()
})
},
closeCreateModal() {
alert('close')
},
}
})
<link rel="stylesheet"
type="text/css"
href="https://cdn.jsdelivr.net/npm/#quasar/extras/material-icons/material-icons.css">
<link rel="stylesheet"
type="text/css"
href="https://cdn.jsdelivr.net/npm/quasar/dist/quasar.min.css">
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/quasar/dist/quasar.umd.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="q-app">
<q-dialog v-model="uploadForm"
transition-show="slide-up"
transition-hide="slide-down"
persistent>
<q-card style="width: 700px; max-width: 50vw;">
<q-card-section>
<div class="text-h6">Add Product</div>
</q-card-section>
<q-card-section class="q-pt-none">
<div class="q-pa-md">
<q-form #submit="createProduct"
class="q-gutter-md">
<q-input outlined
label="Product name"
v-model="data.productName"
:rules="[val => !!val || 'Field is required']"></q-input>
<q-file multiple outlined v-model="data.picture" label="Outlined" accept="image/png,jpg/jpeg"
:rules="[val => !!val || 'Field is required']">
<template v-slot:prepend>
<q-icon name="attach_file" ></q-icon>
</template>
</q-file>
<q-input outlined
label="Description"
v-model="data.description"
:rules="[val => !!val || 'Field is required']"></q-input>
<q-input prefix="₱ "
type="number"
outlined
label="Price"
v-model="data.price"
:rules="[val => !!val || 'Field is required']"></q-input>
<q-select square
outlined
v-model="data.category_id"
:options="categories"
option-value="id"
option-label="categoryName"
label="Category"
:rules="[val => !!val || 'Field is required']"
></q-select>
<div>
<q-btn label="Submit"
color="primary"
type="submit"></q-btn>
<q-btn label="Cancel"
#click="closeCreateModal"
flat class="q-ml-sm"></q-btn>
</div>
</q-form>
</div>
</q-card-section>
</q-card>
</q-dialog>
</div>
if you see the log the "picture" attribute has an array of Object File
I leave the backend processing (laravel) at your discretion
I think it would be easier if you share a link with your problem for future reference
https://jsfiddle.net/idkc/L8xn0puq/52/

Upload Image in Vue Component with Laravel

I am making a simple website that has a feature to upload images. I tried it Laravel way which I made it in blade template and it works fine. Now I am trying to make it inside Vue Components
Here's my Create.vue
<template>
<div>
<div class="row">
<input type="hidden" name="_token" :value="csrf">
<div class="col-md-5">
<div class="detail-container">
<label for="title">Book Title:</label>
<input type="text" name="title" id="title" v-model="book_title" class="form-control">
</div>
<div class="detail-container">
<label for="title">Book Description:</label>
<textarea type="text" name="description" id="description" v-model="book_description" class="form-control" rows="5"></textarea>
</div>
<div class="detail-container">
<label for="title">Tags:</label>
<multiselect v-model="tags" :show-labels="false" name="selected_tags" :hide-selected="true" tag-placeholder="Add this as new tag" placeholder="Search or add a tag" label="name" track-by="id" :options="tagsObject" :multiple="true" :taggable="true" #tag="addTag" #input="selectTags">
<template slot="selection" slot-scope="tags"></template>
</multiselect>
</div>
</div>
<div class="col-md-7">
<!-- BOOK COVER WILL GO HERE -->
<div class="detail-container">
<label>Book Cover:</label>
<input type="file" class="form-control-file" id="book_cover" name="selected_cover" #change="onFileChange">
<small id="fileHelp" class="form-text text-muted">After you select your desired cover, it will show the preview of the photo below.</small>
<div id="preview">
<img v-if="url" :src="url" height="281" width="180" />
</div>
</div>
</div>
<div class="detail-container" style="margin-top: 20px;">
<button class="btn btn-primary" #click="saveBook()">Next</button>
</div>
</div>
</div>
</template>
<script>
import Multiselect from 'vue-multiselect'
// register globally
Vue.component('multiselect', Multiselect)
export default {
// OR register locally
components: { Multiselect },
data () {
return {
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
url: null,
selected_cover: null,
tags: [],
tagsObject: [],
selected_tags: [],
book_title: '',
book_description: ''
}
},
methods: {
getTags() {
let vm = this;
axios.get('/admin/getTags').then(function(result){
let data = result.data;
for(let i in data) {
vm.tagsObject.push({id: data[i].id, name: data[i].name});
}
});
},
addTag (newTag) {
const tag = {
name: newTag,
id: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
}
this.tagsObject.push(tag);
this.tags.push(tag);
},
selectTags(value) {
this.selected_tags = value.map(a=>a.id);
},
onFileChange(e) {
const file = e.target.files[0];
this.url = URL.createObjectURL(file);
this.selected_cover = file;
},
saveBook() {
const fd = new FormData();
fd.append('image', this.selected_cover, this.selected_cover.name)
console.log(this.selected_cover);
var book_details = {
'title': this.book_title,
'description': this.book_description,
'book_cover': this.selected_cover,
'tags': this.selected_tags
};
axios.post('/admin/saveBook', book_details).then(function(result){
console.log('done')
})
}
},
created() {
this.getTags();
}
}
</script>
<!-- New step!
Add Multiselect CSS. Can be added as a static asset or inside a component. -->
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
and here's my controller
public function store(Request $request)
{
$this->validate(request(), [
'title' => 'required|min:5',
'description' => 'required|min:10',
'book_cover' => 'required|image|mimes:jpeg,jpg,png|max:10000'
]);
// File Upload
if($request->hasFile('book_cover')) {
$fileNameWithExt = $request->file('book_cover')->getClientOriginalName();
// GET FILE NAME
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
// GET EXTENSION
$extension = $request->file('book_cover')->getClientOriginalExtension();
// File Unique Name
$fileNameToStore = $filename. '_'. time().'.'.$extension;
$path = $request->file('book_cover')->storeAs('public/book_covers', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$book = new Book;
$book->title = request('title');
$book->description = request('description');
$book->book_cover = $fileNameToStore;
$book->save();
$book->tags()->sync($request->tags, false);
return back()->with('success', 'Book Created Successfully!');
}
I never touched my controller because this is what I used when I do this feature in Laravel Way but when I save it, the details are being saved but the image is not uploading instead it saves noimage.jpg in the database. Does anyone know what I am doing wrong?
i tried to add this part const fd = new FormData(); in book_details but when i console.log(fd) it returned no data.
you should pass the fd object and not the book_details in your POST request.
you could do it something like this.
onFileChange(e) {
const file = e.target.files[0];
// this.url = URL.createObjectURL(file);
this.selected_cover = file;
},
saveBook() {
const fd = new FormData();
fd.append('image', this.selected_cover)
fd.append('title', this.book_title)
fd.append('description', this.book_description)
fd.append('book_cover', URL.createObjectURL(this.selected_cover))
fd.append('tags', this.selected_tags)
axios.post('/admin/saveBook', fd).then(function(result){
console.log('done')
})
}
and also, you can't just console.log the fd in the console. what you can do instead is something like this
for (var pair of fd.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
FormData is a special type of object which is not stringifyable and cannot just be printed out using console.log. (link)

Uploading files with VueJS, axios and Laravel

Hello I am building one project. Where user can send up to 5 images and up to 10 songs with the text. But when I send request to the server, where I handle with Laravel, I can't get those files.
// my data object from VueJS
data() {
return {
formData: new FormData(),
pikir: {
body: '',
},
isLoading: false,
images: [],
songs: [],
}
}
// imagePreview method from VuejS
imagePreview(event) {
let input = event.target;
if (input.files[0]) {
if (input.files.length <= 5) {
for (let i = 0; i < input.files.length; i++) {
let reader = new FileReader();
reader.onload = e => {
this.images.push(e.target.result);
}
reader.readAsDataURL(input.files[i]);
}
Array.from(Array(event.target.files.length).keys())
.map(x => {
this.formData
.append('images',
event.target.files[x], event.target.files[x].name);
});
} else {
alert('You can upload up to 5 images');
}
}
}
// musicPreview method from VueJS
musicPreview(event) {
let input = event.target;
if (input.files.length <= 5) {
for (let i = 0; i < input.files.length; i++) {
this.songs.push(input.files[i].name.replace('.mp3', ''));
}
Array.from(Array(event.target.files.length).keys())
.map(x => {
this.formData
.append('songs',
event.target.files[x], event.target.files[x].name);
});
} else {
alert('You can upload up to 10 songs');
}
}
// sharePikir method from VueJS
sharePikir() {
this.formData.append('body', this.pikir.body);
axios.put('/api/pikirler', this.formData)
.then(response => {
this.pikir.body = '';
this.isLoading = false;
})
.catch(() => {
this.isLoading = false;
});
},
<form action="#" id="share-pikir">
<label for="pikir">
Näme paýlaşmak isleýärsiňiz? {{ pikirSymbolLimit }}
</label>
<input type="text" name="pikir" id="pikir" maxlength="255"
v-model="pikir.body"
#keyup="handleSymbolLimit()">
<div class="emoji">
<i class="fa fa-smile-o"></i>
</div>
<div class="photo-music left">
<label for="music-upload">
<i class="fa fa-music"></i>
</label>
<input type="file" name="songs[]" id="music-upload"
accept="audio/mp3"
#change="musicPreview($event)"
multiple>
<i class="divider"></i>
<label for="image-upload">
<i class="fa fa-image"></i>
</label>
<input type="file" name="images[]" id="image-upload"
#change="imagePreview($event)"
multiple>
</div>
<div class="share right">
<button
:class="{ 'btn-medium': true, 'is-loading': isLoading }"
#click.prevent="sharePikir($event)">
Paýlaşmak
</button>
</div>
</form>
I put my front end stuff above and in my Laravel side I just return all requests:
public function store(){
return request()->all();
}
And these are what I get from request:
I couldn't found what is wrong. Thank you in advance.
Oh yeah! you're missing this part. You need to define this.
axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';
this my solutuion
export default {
data (){
return {
attachment : { name : null,file: null }
}
},
methods : {
onFileChange(event) {
this.attachment.file = event.target.files[0]
},
attachmentCreate() {
var form = new FormData();
form.append('name',this.attachment.name);
form.append('file',this.attachment.file);
this.$http.post('attachment',form).then(response=>{
console.log("oke")
})
},
}
}
<input type="file" class="form-control" #change="onFileChange">
Check this post, maybe your problem is solved:
[https://stackoverflow.com/questions/55895941/success-upload-file-via-postman-but-fail-on-front-end-vue/73698108#73698108][1]

Resources