I'm trying to make a post request each time one of the files I have in 'this.photos' is appended to formData. Right now, I have the correct number of API calls being made, but they're all just the last photo uploaded being repeated.
My Backend doesn't allow for multiple items in one field, so I need to make as many API calls as there are files added on the frontend
<template>
<div class="container">
<div class="large-12 medium-12 small-12 cell">
<label>
Files
<input type="file" id="files" ref="photos" multiple v-on:change="handleFilesUpload()" />
</label>
<button v-on:click="submitFiles()">Submit</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
photos: ""
};
},
methods: {
submitFiles(axios) {
//let formData = new FormData();
for (var i = 0; i < this.photos.length; i++) {
let formData = new FormData();
let photo = this.photos[i];
formData.append("photos", photo);
const config = {
headers: {
"content-type": "multipart/form-data; "
}
};
this.$axios
.post(`/api/v1/photos/`, formData, config)
.then(response => {
console.log("Successfully Submitted Images");
})
.catch(error => {
console.log(error);
});
}
},
handleFilesUpload() {
this.photos = this.$refs.photos.files;
console.log(this.photos);
}
}
};
</script>
I feel like it's just something simple that I'm missing 😖, so thanks for the help!
Try this:
submitFiles(axios) {
let formData = new FormData();
for (var i = 0; i < this.photos.length; i++) {
let photo = this.photos[i];
formData.append("photos", photo);
const config = {
headers: {
"content-type": "multipart/form-data; "
}
};
}
this.$axios
.post(`/api/v1/photos/`, formData, config)
.then(response => {
console.log("Successfully Submitted Images");
})
.catch(error => {
console.log(error);
});
},
//let formData = new FormData();
for (var i = 0; i < this.photos.length; i++) {
let formData = new FormData();
Fix: Move the formData declaration inside of the for loop. If it's outside, the final photo gets queued 3 times before being posted. The fix makes sure only the photo in question is queued and sent
Related
I have an issue with the library vue-signature-pad, it works ok if I sign on the modal in a cellphone and I store the image, the size is ok but if I sign on the modal in the computer when I store the image it saves and I look at it.. it is very small.
So I wonder why if I sign in cellphone it stores in a good size but if I do same in a laptop I get a small signature?
My code:
<b-modal ref="signature_modal" size="xl" hide-footer title="Firmar en el recuadro blanco">
<VueSignaturePad
id="signature"
:customStyle="sigStyle"
width="100%"
height="200px"
ref="signaturePad"
:options="{onBegin: () => {$refs.signaturePad.resizeCanvas()}}"
/>
</b-modal>
export default {
created() {
},
mounted() {
this.$refs.signaturePad.$refs.signaturePadCanvas.width = 250
this.$refs.signaturePad.$refs.signaturePadCanvas.height = 250
},
methods: {
fileData() {
this.settlement_id = this.$route.params.id;
this.rut = this.$route.params.rut;
this.month = this.$route.params.month;
this.year = this.$route.params.year;
},
forceFileDownload(response) {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'liquidacion.pdf')
document.body.appendChild(link)
link.click()
},
undo() {
this.$refs.signaturePad.undoSignature();
},
save() {
const { isEmpty, data } = this.$refs.signaturePad.saveSignature();
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
console.log(isEmpty);
console.log(data);
let formData = new FormData();
formData.append('signature', data);
axios.post('/api/signature/store?api_token='+App.apiToken, formData, config)
.then(function (response) {
currentObj.success = response.data.success;
})
.catch(function (error) {
console.log(error);
})
.finally(() => {
this.loading = false;
this.$awn.success("Usted firmo correctamente. Ya puede descargar el documento.", {labels: {success: "Éxito"}});
this.$router.push('/signature/show/'+this.$route.params.id+'/'+this.$route.params.rut+'/'+this.$route.params.month+'/'+this.$route.params.year+'');
});
}
Here I have written a code for multi upload images. And the functionality i dont know where I am going wrong. like while i am uploading an image. So in console terminal I am seeing only image name not image. So please tell me where I am going wrong I want to save the image in backend but I am getting only image name in vue code. So please tell me where I am going wrong. Please help me
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<h2>Multiple Files</h2>
<hr/>
<label>
<span>Files</span>
<input type="file" multiple #change="handleFileUploads($event)" />
<ul v-if="files.length">
<li v-for="(name, i) in filesNames" :key="i">{{ name }}</li>
</ul>
</label>
<div>
<img v-for="image in images" :src="image" />
</div>
<br />
<button #click="submitFiles()">Submit</button>
</div>
vue.js
Vue.config.productionTip = false;
new Vue({
el: '#app',
data() {
return {
files: [],
images: [],
}
},
computed: {
filesNames() {
const fn = []
for (let i = 0; i < this.files.length; ++i) {
fn.push(this.files.item(i).name)
}
return fn
}
},
methods: {
handleFileUploads(event) {
this.files = event.target.files;
this.images = [...this.files].map(URL.createObjectURL);
},
// how to access img_fna or sal to backend in from this snippet of code.
submitForm: function(){
const img_fna = []
for (let i = 0; i < this.files.length; ++i) {
let file = this.files[i];
img_fna.push(file)
}
var reader;
var file;
var i;
const sal = []
for (i = 0; i < files_s.length; i++) {
file = files_s[i];
reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
sal.push(e.target.result);
};
})(file);
reader.readAsDataURL(file);
}
axios({
method : "POST",
url: "{% url 'service-ad' %}", //django path name
headers: {'X-CSRFTOKEN': '{{ csrf_token }}',
'Content-Type': 'application/json'},
data : {
"images": sal,
"image_url": img_fna,
},//data
}).then(response => {
this.success_msg = response.data['msg'];
}).catch(err => {
this.err_msg = err.response.data['err'];
});
}
}
})
If I understand you correctly, you want to post your images list to backend, but you don't know how to get data from files like this:
enter image description here
and send data to backend. And in backend, you can only see image name, am i right?
If so, here is my example code:
async submitFile() {
let filelist = [];
for (let i = 0; i < this.files.length; ++i) {
filelist.push(
await (async (cur) => {
return new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onload = () => {
resolve(fr.result);
};
fr.readAsDataURL(cur);
});
})(this.files.item(i))
);
}
let formData = new FormData();
formData.append("files", filelist);
axios.post('/multiple-files', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function() {
console.log('SUCCESS!!');
})
.catch(function() {
console.log('FAILURE!!');
});
},
The focus is to use FileReader.readAsDataURL to get the image as base64 encoded data. Then you have image data in the backend like this:
enter image description here
Good day,
I'm working on a project that have an import functionality. How can I retrieve the data inside of the csv file?. It is possible to retrieve it in front end or should I use axios.post?
Here is my code so far:
<input
type="file"
id="files"
style="display: none;"
accept=".csv"
ref="file"
v-on:change="handleFileUpload()"
/>
<button #click="onImport"> Import </button>
In my method :
data: {
file: '',
},
methods: {
onImport() {
$('#files').click();
},
handleFileUpload() {
this.file = this.$refs.file.files[0];
let formData = new FormData();
formData.append('file', this.file);
}
Thank you in advance for the help
You can use FileReader like so:
async handleFileUpload() {
this.file = this.$refs.file.files[0];
const reader = new FileReader();
reader.readAsText(this.file);
reader.onload = () => {
console.log(reader.result); // contains the file content as a string
};
reader.onerror = () => {
console.log(reader.error);
};
const formData = new FormData();
formData.append('file', this.file);
// Send your file to your server and retrieve the response
const res = await axios.post('https://example.com/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
}
It works on all major browsers also.
I have vue SPA and I trying to upload some images and text. I try using postman to test my server code and it's work, but my client-side still error.
I think I'm still mistaken for handle req.file.
addImage.vue
<template>
<div>
<b-form-group label-cols-sm="3" description="image title" label="Title">
<b-form-input v-model="newImage.title"></b-form-input>
</b-form-group>
<b-form-group label="my Image" label-for="file" label-cols-sm="2">
<b-form-file id="file" v-model="newImage.image"></b-form-file>
</b-form-group>
<b-button variant="primary" class="pl-5 pr-5" #click.prevent="addImage">Save</b-button>
</div>
</template>
<script>
export default {
data() {
return {
newImage: {
title: '',
image: null,
},
};
},
methods: {
addImage() {
this.$store.dispatch('addProduct', this.newProduct);
}
},
};
store.js
actions: {
addImage(context, newImage) {
const config = {
headers: {
token: localStorage.getItem('token'),
},
};
Axios
.post(`${baseUrl}/product`, newImage, config)
.then(({ newImage }) => {
context.commit('ADD_IMAGE', newImage);
})
.catch((err) => {
console.log(err.message);
});
}
}
When you want to upload an image you have to set the content type and create FormData, like this:
let data = new FormData();
for (var i = 0; i < files.length; i++) {
let file = files.item(i);
data.append('images[' + i + ']', file, file.name);
}
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
return axios.post('/api/images', data, config)
Hello I am trying to attach file for axios.post however when I do a console.log() the formData is empty so here is what I am working with.
On my vue form
<form #submit.prevent="uploadTodos">
<div>
<input type="file" v-on:change="selectedFile($event)">
<label>Choose file</label>
</div>
<button type="submit">Submit</button>
</form>
Here is the data object
data() {
return {
file: null,
}
}
and method I have for the selectedFile on change event
selectedFile(event) {
this.file = event.target.files[0]
},
and here is the submit event method
uploadTodos() {
let formData = new FormData
formData.append('file', this.file)
this.$store.dispatch('uploadTodos', formData)
}
and here is the store method being dispatch
uploadTodos(context, file) {
console.log(file)
axios.post('/import', file,{ headers: {
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log(response.data)
context.commit('importTodos', response.data)
})
.catch(error => {
console.log(error.response.data)
})
}
and when I console.log(file) I get the formData I created in the uploadTodos() method however it is empty, So I am trying to figure out why it is empty?
any help would be greatly appreciated