I am Continuing My Form Upload with Multiple Images in Extension to the Object oriented Forms
Tutotrial Of Vue JS 2 but found so many problems but finally i am struck at a point my code is
//Form.js
import Errors from './Errors';
class Form {
/**
* Create a new Form instance.
*
* @param {object} data
*/
constructor(data) {
this.originalData = data;
for (let field in data) {
this[field] = data[field];
}
this.errors = new Errors();
}
/**
* Fetch all relevant data for the form.
*/
data() {
let data = new FormData();
for (let property in this.originalData) {
data.append(property,this[property]);
}
return data;
}
/**
* Reset the form fields.
*/
reset() {
for (let field in this.originalData) {
this[field] = '';
}
this.errors.clear();
}
/**
* Send a POST request to the given URL.
* .
* @param {string} url
*/
post(url) {
return this.submit('post', url);
}
/**
* Send a PUT request to the given URL.
* .
* @param {string} url
*/
put(url) {
return this.submit('put', url);
}
/**
* Send a PATCH request to the given URL.
* .
* @param {string} url
*/
patch(url) {
return this.submit('patch', url);
}
/**
* Send a DELETE request to the given URL.
* .
* @param {string} url
*/
delete(url) {
return this.submit('delete', url);
}
/**
* Submit the form.
*
* @param {string} requestType
* @param {string} url
*/
submit(requestType, url) {
return new Promise((resolve, reject) => {
axios[requestType](url, this.data(),{headers:{'Content-Type':'multipart/form-data'}})
.then(response => {
this.onSuccess(response.data);
resolve(response.data);
})
.catch(error => {
this.onFail(error.response.data);
reject(error.response.data);
});
});
}
/**
* Handle a successful form submission.
*
* @param {object} data
*/
onSuccess(data) {
alert(data.message); // temporary
this.reset();
}
/**
* Handle a failed form submission.
*
* @param {object} errors
*/
onFail(errors) {
this.errors.record(errors);
}
}
export default Form;
// App.js
import Form from "./Form";
var app = new Vue({
el: '#app',
data: {
form: new Form({
name: '',
description: '',
image:[]
})
},
methods: {
onFileChange(e){
let selDiv = document.querySelector('#preview');
if (!e.target.files || !window.FileReader) return;
selDiv.innerHTML = "";
let files = e.target.files, filesArr = Array.prototype.slice.call(files);
filesArr.forEach(f => {
if (!f.type.match('image.*')) {
e.target.value = e.target.type = '';
e.target.type = 'file';
alert('We accept only images');
}
app.$data.form.image.push(f);
var reader = new FileReader();
reader.onload = function (c) {
var html = "<img src='" + c.target.result + "' class='preview-img' height='80'>";
selDiv.innerHTML += html;
}
reader.readAsDataURL(f);
});
},
onSubmit() {
this.form.post('/projects')
}
}
});
here I want to know how to add file object to the FormData() and send it to the server