Vuejs. I can't transfer data to an Object - vue.js

I would like to catch uploaded file in FilePond. but the base64 of the file isn't transfered to my object. Any solutions?
In template
<FilePond
v-on:addfile="catch"
/>
In Data
data:function() {
return {
image:'',
}}
in Method
catch: function(fieldName, file) {
console.log('#', file.file) // The Blop format file appears in console
const reader = new FileReader(); //convert to base64
reader.readAsDataURL(file.file);
reader.onloadend = function() {
console.log('yy',reader.result); // Base64 image appears in console
(600000 carac)
this.image= reader.result ; // HERE, the object still blank
} },
Error in console :
Uncaught TypeError: Cannot set property 'image' of undefined
at FileReader.reader.onloadend

this keyword is shadowed by the onloadend function, save this before defining the function and then reference it inside:
methods: {
catch: function(fieldName, file) {
// ...
var ref = this
reader.onloadend = function() {
ref.image= reader.result // use ref here
}
// ...
}
}

Related

Using dropzone.js in vue, calling function with image file name

I'm having a hard time getting anything to work with this the way I need it, but I have a working dropzone instance in my Vue project.
I can upload the image and call functions within the dropzone code, however, I need to call a function directly from the form in the html in order to send the 'card' object.
All I need to do is call a function when a file is added through the dropzone form, with the filename.
My code:
<div class="uk-width-3-10">
<form v-on:change="imageChange(card)" method="post" action="{{url('product/parts/upload/store')}}" enctype="multipart/form-data"
class="dropzone" v-bind:id="'dropzone-'+i">
</form>
</div>
...
imageChange(Card){
console.log('working');
},
addCard(){
Vue.nextTick(function () {
new Dropzone("#dropzone-"+cardIndex, {
maxFilesize: 12,
renameFile: function (file) {
var dt = new Date();
var time = dt.getTime();
return time + file.name;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
removedfile: function (file) {
console.log(file.upload.filename);
var name = file.upload.filename;
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
},
init: function() {
this.on("addedfile",
function(file) {
instance.imageZoneNames.push({name: file.upload.filename});
console.log(file);
console.log(instance.imageZoneNames);
});
}
});
});
}
Dropzone has many events, You used removedfile() event! there is another event called addedfile() and executes when a file is added to the dropzone list
imageChange(card) {
console.log(card)
},
addCard() {
Vue.nextTick(() => {
new Dropzone('#dropzone-` + cardIndex, {
addedfile(file) {
this.imageChange(file);
}
}
}
}

Vue / Vuetify - this.$refs.form.reset() error in file input

I was using this.$refs.form.reset() for my modal and all the fields are cleared not until I used the v-file-input field. The error produces Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
If I manually set the the value of the v-file-input into null, everything is working fine. How do I retain using this.$refs.form.reset() without this error?
<v-file-input
v-model="tableItem.photo"
accept="image/png, image/jpeg, image/bmp"
placeholder="Pick an avatar"
prepend-icon="mdi-camera"
label="Avatar"
#change="getImagePreviews()"
></v-file-input>
getImagePreviews() {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageURL = reader.result
})
reader.readAsDataURL(this.tableItem.photo)
},
closeModal() {
this.tableItem.photo = null // this is working but I need to remove this.$refs.form.reset()
this.$refs.form.reset()
this.$refs.form.resetValidation()
}
Since the readAsDataURL() function accepts only Blob data, you can check if the parameter is of Blob type:
getImagePreviews() {
if (this.tableItem.photo instanceof Blob){
this.reader.readAsDataURL(this.tableItem.photo)
}else{
this.imageURL = null
}
},
Also, you may want to initialize the reader in the mounted hook:
data: ()=>({
reader: null
}),
mounted(){
this.reader = new FileReader();
this.reader.addEventListener("load", () => {
this.imageURL = this.reader.result
})
}

How in bootstrap-vue convert FileReader to blob and upload to server?

In #vue/cli 4.1.1 app I use bootstrap-vue and b-form-file conponent for images uploading
https://bootstrap-vue.js.org/docs/components/form-file/#multiple-files
with definition :
<b-form-file
id="upload_ad_image"
v-model="new_upload_ad_image"
:state="Boolean(new_upload_ad_image)"
placeholder="Choose a file or drop it here..."
drop-placeholder="Drop file here..."
accept="image/jpeg, image/png, image/gif"
></b-form-file>
<div ref="uploaded_img_preview" id="uploaded_img_preview" class="m-2" >Uploaded image preview :</div>
I found snippet https://codepen.io/Tenderfeel/pen/rgqWXR
and using it I show selected file on my form for preview.
Next I need to upload it on the server. I have an expierence of uploading image as blog using code like :
fetch(this.taskRow.imageFile.blob).then(function (response) {
if (response.ok) {
return response.blob().then(function (imageBlob) {
let imageUploadData = new FormData()
imageUploadData.append('id', self.taskRow.id)
imageUploadData.append('image', imageBlob)
imageUploadData.append('image_filename', self.taskRow.imageFile.name)
But I need to convert uploading image to blob. I use method when image is selected:
But got error : Error in callback for watcher "new_upload_ad_image": "InvalidStateError: Failed to execute 'readAsDataURL' on 'FileReader': The object is already busy reading Blobs
watch: {
new_upload_ad_image(val) {
if (!val) return;
if (this.previewImg) {
this.previewImg.remove();
}
const img = document.createElement("img");
img.classList.add("obj");
img.file = this.new_upload_ad_image;
console.log('img.file::')
console.log(img.file)
this.previewImg = img;
console.log('this.$refs.uploaded_img_preview::')
console.log(this.$refs.uploaded_img_preview)
console.log('img::')
console.log(img)
this.$refs.uploaded_img_preview.appendChild(img);
const fileReader = new FileReader();
fileReader.onload = (e) => {
this.previewImg.src = e.target.result;
};
fileReader.readAsDataURL(this.new_upload_ad_image);
console.log('fileReader::')
console.log(fileReader)
let blobObj= fileReader.readAsDataURL(img.file) // RAISE ERROR :
console.log('blobObj::')
console.log(blobObj)
}
},
What I see in the console : https://imgur.com/a/2EZxq9C
How to get blob and upload it on server?
MODIFIED BLOCK :
having file input with id="upload_ad_image" defined :
<b-form-file
id="upload_ad_image"
v-model="new_upload_ad_image"
:state="Boolean(new_upload_ad_image)"
placeholder="Choose a file or drop it here..."
drop-placeholder="Drop file here..."
accept="image/jpeg, image/png, image/gif"
></b-form-file>
I run fetch and see that image blob is invalid and file is created, but it is invalid
I have :
var self = this
const upload_ad_image = document.getElementById('upload_ad_image')
console.log('upload_ad_image::')
console.log(upload_ad_image)
console.log('upload_ad_image.files::')
console.log(upload_ad_image.files[0])
if (typeof upload_ad_image.files[0] == 'undefined') {
self.showPopupMessage('Ad image upload', 'Invalid image !', 'warn')
return
}
fetch(upload_ad_image.files[0].blob).then(function (response) {
if (response.ok) {
return response.blob().then(function (imageBlob) {
console.log('imageBlob::')
console.log(imageBlob) // Looks like this var has invalid content(printscreen below)!
let imageUploadData = new FormData()
imageUploadData.append('ad_id', self.editableAd.id)
imageUploadData.append('main', self.new_upload_ad_image_main)
imageUploadData.append('info', self.new_upload_ad_image_info)
imageUploadData.append('image', imageBlob)
imageUploadData.append('image_filename', upload_ad_image.files[0].name)
I see in console : https://imgur.com/a/4ees55C
What is wrong and how it can be fixed ?
"bootstrap-vue": "^2.3.0",
"vue": "^2.6.11",
Thanks!
File objects do inherit from the Blob interface.
All you can do with a Blob, you can also do it with a File, so in your code you can directly append this.new_upload_ad_image to your FormData.
const inp = document.getElementById('inp');
inp.onchange = (evt) => {
const formData = new FormData();
formData.append( 'my-file', inp.files[0], 'file.ext' );
// check it's correctly in the FormData
console.log( [...formData.entries()] );
};
<input type="file" id="inp">

VueJS file upload not accepting file

I'm working on a file upload image preview with VueJS and I'm having an issue where...
1. - file get uploaded by user
2. - preview comes up beside the input field
3. - input field now says there is no image uploaded though there is the preview.
here is the html:
<input type='file' accept='image/*' #change="onChange" name='file' />
<img width='200' :src="uploadPreview" alt='preview' />
here is my vueJs code:
data: function() { return {
uploadPreview : "",
}
},
methods : {
onChange(e) {
if (! e.target.files.length) return;
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = e => {
this.uploadPreview = e.target.result; // if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
};
},
}
there's something with that line that I commented in the code there.
this.uploadPreview = e.target.result;
if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
Why is this not working? Why does the input field value for the file reset after simply setting uploadPreview to some binary image data??? Banging my head on this table once more.
I suggest you debugging points. Try and let me know.
data: function() { return {
uploadPreview : "ABCD",
}
},
methods : {
onChange(e) {
if (! e.target.files.length) return;
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = e => {
console.log("FIRST SEE WHAT'S INSIDE THE RESULTS",e.target.result);
console.log("SECOND MAKE SURE YOU CAN ACCESS",this.uploadPreview) // this should print ABCD
this.uploadPreview = e.target.result; // if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
};
},
}
and finally
<img width='200' :src="uploadPreview" :alt='uploadPreview' />
(alt should equals to image data)

get is not defined when trying to extends JSONSerializer

I try to define my custom serializer by extending DS.JSONSerialzer.
I pick the serialize function without modifications but when i run Ember,i get this error:
ReferenceError: get is not defined
This is my code :
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
if (options && options.includeId) {
var id = get(record, 'id');
if (id) {
json[get(this, 'primaryKey')] = id;
}
}
record.eachAttribute(function(key, attribute) {
this.serializeAttribute(record, json, key, attribute);
}, this);
record.eachRelationship(function(key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(record, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(record, json, relationship);
}
}, this);
return json;
},
});
I didn't change any code. This is the original. Why get is suddenly undefined? It's imported in line 1 in the original file JSONSerialiser
Can you help me?
They have get defined in the scope when creating the serializer, but that doesn't extend outside of their scope into your files.
var get = Ember.get;
var isNone = Ember.isNone;
var map = Ember.ArrayPolyfills.map;
var merge = Ember.merge;
Either replace all of the get methods with Ember.get or define get to be Ember.get