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.
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+'');
});
}
I am developing a system with nuxt js and jest that in part of that I want to upload an image.
Here's my html code:
<input
id="photo"
ref="photo"
type="file"
name=""
class="form-control d-flex"
#change="uploadPhoto"
>
Here's my uploadPhoto function in nuxt js:
uploadPhoto () {
const file = this.$refs.photo.files[0]
// upload photo
const formData = new FormData()
formData.append('photo', file)
const returnedData = await this.$axios.$post('/api/photo/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
The question is:
How may I mock uploading photo in jest to test my code?
My jest code is something like this:
test('uploading photo test', () => {
wrapper = mount(UploadPhotoComponent, {
stubs: {
NuxtLink: true
},
mocks: {
$auth: {
loggedIn: true,
$storage: {
_state: {
'_token.local': 'api bearer token'
}
}
},
$axios: {
$post: jest.fn(() => {
return Promise.resolve({
status: 200,
message: 'photo was uploaded successfully.',
entire: []
})
})
}
}
})
})
I don't know how to test uploading file in jest using mocks.
Can anyone help me?
Finally, I have realized how to do that. First of all generate an image blob and file:
import fs from 'fs';
import path from 'path';
const dummyImgData = fs.readFileSync(
path.join(__dirname, '../../libs/dummy-img-2.jpeg')
);
const fbParts = [
new Blob([dummyImgData], {
type: 'image/jpeg'
}),
'Same way as you do with blob',
new Uint16Array([999999999999999])
];
const fbImg = new File(fbParts, 'sample.png', {
lastModified: new Date(2020, 1, 1),
type: 'image/jpeg'
});
And after assign it to $refs object:
wrapper.vm.$refs = {
photo: {
files: [
fbImg
]
}
}
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
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
A question about the quasar framework uploader component.
I need to post the images to a URL that will rename the uploaded file and return the full path.
I'm using the upload-factory and axios
But I'm having problems understanding exactly how to pass the file to axios as if it was just an input type file.
Basically I need to make it as If I'm sending a form with a single input file like this:
<input type="file" name="banner">
This is the component:
<q-uploader
url=""
extensions=".gif,.jpg,.jpeg,.png"
:filter="filterFiles"
:upload-factory="uploadFile" />
This is the upload method, but I keep getting an error response from the server.
uploadFile (file, updateProgress) {
const formData = new FormData()
formData .set('banner', file)
var headers = {
'Content-Type': 'multipart/form-data'
}
axios.post('http://someurl/uploadFile', formData , headers)
.then(function (response) {
console.log(response)
})
.catch(function (response) {
console.log(response)
})
}
If I post a plain html form with method="post" enctype="multipart/form-data" and a
<input type="file" name="banner">
I get my OK response from the server with the processed/uploaded image URL
I have successfully done uploading of the file to python API.
V1 Update
Use #added -> function(files) method.
Also extensions property is removed now use accept
This is the component:
<q-uploader
url=""
extensions=".gif,.jpg,.jpeg,.png"
#add="file_selected"
/>
<q-btn #click="uploadFile()">Upload</q-btn>
Data:
data() {
return {
selected_file:'',
check_if_document_upload:false,
}
}
Methods
file_selected(file) {
this.selected_file = file[0];
this.check_if_document_upload=true;
},
uploadFile() {
let fd = new FormData();
fd.append("file", this.selected_file);
axios.post('/uploadFile', fd, {
headers: { 'Content-Type': undefined },
}).then(function(response) {
if(response.data.ok) {
}
}.bind(this));
}
This is working fine for me.
I have successfully done direct uploading of the file on a button click to python API. But in vue3 and Quasar 2 with some additional formData. Thought might be helpful
This is component:
<q-btn
label="Upload"
#click="openFilePicker"
/>
<q-uploader
ref="uploadFile"
class="hidden"
accept=".jpg, .jpeg, .png"
#added="uploadFileFn"
/>
Setup:
setup() {
return {
uploadFile: ref(null),
}
},
Methods:
openFilePicker() {
this.$refs.uploadFile.pickFiles();
},
uploadFileFn(file) {
this.uploadFile = file[0];
let fd = new FormData();
fd.append("file", this.uploadFile);
fd.append("id", "1");
fd.append("name", "test_user");
this.$axios.post('/upload_file_with_additional_form_data', fd, {
headers: {'Content-Type': undefined},
}).then(
function (response) {
if (response.data.success) {
console.log(response)
}
}.bind(this))
}
This is working fine for me.