VueJS FileReader - vue.js

I'm trying to use ExcelJS in Vue and I need FileReader to read and parse the files but I'm getting errors. How do I use FileReader with VueJS?
Input Form
<input type="file"
id="importProductionSchedule"
name="importProductionSchedule"
#change="checkFile($event)"
ref="importProductionSchedule"
>
checkFile method
checkFile() {
let reader = new FileReader()
let self = this
reader.onload = (e) => {
let bstr = e.target.result
let wb = XLSX.read(bstr, {type:'binary'})
let wsname = wb.SheetNames[0]
let ws = wb.Sheets[wsname]
let data = XLSX.utils.sheet_to_json(ws, {header:1})
self.form.filedata = data
self.cols = make_cols(ws['!ref'])
}
reader.onerror = (stuff) => {
console.log("error", stuff)
console.log (stuff.getMessage())
}
// reader.readAsArrayBuffer(event)
reader.readAsBinaryString(event.target.files[0])
},
First of all, logging event.target.files[0] in the console would return the file, but I'm testing both event and event.target.files[0] to make sure.
These are my errors:
event = Uncaught Error: cannot read as File: {"isTrusted":true}
event.target.files[0] = Uncaught Error: cannot read as File: {}

you can use below method
createImage(file) {
let reader = new FileReader()
reader.onload = (event) => {
this.product.image = event.target.result
}
reader.readAsDataURL(file)
}

methods:{
uploadImage(event) {
const image = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(image);
reader.onload = (event) => {
this.previewImage = event.target.result;
};
},
}

Related

Jest test working fine but not updating data in wrapper after await

I am writing my first test in Vue and using jest, the issue I am facing is my function works and I am able to console log the data and see it in the console but the wrapper data has not been updated.
async loadcsv(element=null) {
const reader = new FileReader()
let file = element[0].file
this.toggleLoading()
reader.onload = async (e) => {
try {
//Normalising headers
const results = e.target.result
let resultSplit = results.split('\n')
const header = resultSplit[0]
.toLowerCase()
.replace(/[^a-zA-Z,]/g, '')
.trim()
resultSplit[0] = header
let table = resultSplit.join('\n')
const rows = await d3.csvParse(table) //wrapper data does not update after this line, anything before reflects
await Promise.all(
rows.map(async (row) => {
this.collections.push(row)
}),
)
this.inlineVisibility = false
this.toggleLoading()
this.$refs.modal.hide()
} catch (err) {
this.toggleLoading()
this.inlineNotification('error', 'Unable to process CSV', `${err}.`)
}
}
reader.readAsText(file)
},
}
However data in the wrapper.vm.$data is still empty
collection = []
where as in the console, it shows
collection = [{my test data}]
with at mockConstructor.reader.onload
at the end
How do I get the array that shows I the console?
workingCSV is a string of my CSV file
describe('ModalAddCollectionCSV', () => {
it('Test load csv function', async () => {
const localVue = createLocalVue()
const wrapper = mount(ModalAddCollectionCSV, {
localVue,
propsData: {
visible: true,
},
})
const readAsTextMock = jest.fn()
const dataRead = jest.spyOn(global, 'FileReader').mockImplementation(function () {
const self = this
this.readAsText = readAsTextMock.mockImplementation(() => {
self.onload({ target: { result: workingCSV } })
})
})
const data = wrapper.vm.loadcsv()
expect(wrapper.vm.$data).toContain(data)
})

upload a pdf to s3 from frontend -> node js -> s3

frontend app:
const readURL = (input) => {
if (input.files && input.files[0]) {
let reader = new FileReader();
reader.fileName = input.files[0].name;
reader.onload = async function (e) {
uploadPhoto(reader, e);
};
reader.readAsDataURL(input.files[0]);
}
};
const uploadPhoto = (reader, e) => {
let client = new ServerData();
client.put("/images/upload", {
imageBase64: reader.result,
name: e.target.fileName,
typeOfUpload: "xxxx-bank",
}).then(uploadResult => {
....
})
};
backend node.js
fileContent = base64Image // directly from frontend
fileContent = Buffer.from(base64Image,'base64'); //tried this as well
let params = {
Bucket: 'bucket',
Key: 'name.pdf',
Body: fileContent,
ContentEncoding: 'base64',
ACL: 'private'
}
let upload = new AWS.S3.ManagedUpload({
params: params
});
notice the fileContent
for images it works and i'm using
Buffer.from(base64Image.replace(/^data:image\/\w+;base64,/, ""),'base64');
the solution was
Buffer.from(base64Image.replace(/^data:.+;base64,/, ""),'base64');

Vue and FileReader API: How to wait for image file before uploading?

I am trying to use the FileReader() API and having trouble understanding how to wait for it to finish so that way I can access the data URL and upload it to cloud storage.
Let me explain:
I have the following template:
<input
id="my-file-input"
type="file"
accept="image/*"
#change="fileChangeHandler"
/>
<img src="photo" />
Script:
fileChangeHandler(e) {
const reader = new FileReader()
reader.onload = (e) => {
this.photo = e.target.result
}
reader.readAsDataURL(e.target.files[0])
console.log(this.photo)
const file = this.photo
// convert photo file name to hash
const photoName = uuidv4()
const storageRef = this.$fireStorage.ref()
const photoRef = storageRef.child(
`photos/${this.userProfile.uid}/${photoName}/${photoName}.jpg`
)
const uploadTask = photoRef.putString(file, 'data_url') <--- image not ready yet, thus get console error
Here is screenshot of console error:
How can I successfully await for the file reader to finish before running the .putString() ? Thank you!
You can utilize a Promise and then use async await like below :
async fileChangeHandler(e) {
this.photo = await new Promise(resolve=>{
const reader = new FileReader()
reader.onload = (e) => {
resolve(e.target.result)
}
});
// rest of your code
}

How to sending DOM to Image in server(Vuejs)?

Please can anyone me show how to sending Base64 image into server,I am using Dom to image library.
//My script
import domtoimage from "dom-to-image";
export default {data: function() {return{ post: { image: "" },}
createPost(post) {
var node = document.getElementById("my-node");
domtoimage.toPng(node).then(function(dataUrl) {
var image = new Image();
image.src = dataUrl;
document.body.appendChild(image); }) this.$store.dispatch('createPost', post)},}
//In Action.js
createPost({commit}, post) {axios.post('posts', post).then(res => {commit('CREATE_POST', res.data)})},
imgProfile(event) {
this.image = event.target;
if (this.image.files && this.image.files[0]) {
var reader = new FileReader();
reader.onload = (e) => {
this.imageData = e.target.result;
}
reader.readAsDataURL(this.image.files[0]);
this.SvImage = this.image.files[0];
}
},

How to send image on WEBrtc channel?

I am stuck on sending image via webrtc channel, but I got this error.
Cannot read property 'files' of undefined at SimpleWebRTC
I need help. Thank you in advance.
$("#send-image").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('.output #photo').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
webrtc.sendDirectlyToAll('shareImage', '');
}
});
var input = $('#send-image')[0];
if (input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('.output #photo').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}