Javascript Vue: Where does the variable e in onFileChange(e) originate?
In the following code, there is a variable e in onFileChange(e), where does it originate? It is never declared or imported in the code, so how can it be valid?
Any help would be greatly appreciated.
<template>
<div class="container" style="margin-top: 50px;">
<div class="text-center">
<h4>File Upload with VueJS and Laravel</h4>
<br />
<div style="max-width: 500px; margin: 0 auto;">
<div v-if="success !== ''" class="alert alert-success" role="alert">
{{success}}
</div>
<form #submit="submitForm" enctype="multipart/form-data">
<div class="input-group">
<div class="custom-file">
<input
type="file"
name="filename"
class="custom-file-input"
id="inputFileUpload"
v-on:change="onFileChange"
/>
<label class="custom-file-label" for="inputFileUpload"
>Choose file</label
>
</div>
<div class="input-group-append">
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</div>
<br />
<p class="text-danger font-weight-bold">{{filename}}</p>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log("Component successfully mounted.");
},
data() {
return {
filename: "",
file: "",
success: ""
};
},
methods: {
onFileChange(e) {
//console.log(e.target.files[0]);
this.filename = "Selected File: " + e.target.files[0].name;
this.file = e.target.files[0];
},
submitForm(e) {
e.preventDefault();
let currentObj = this;
const config = {
headers: {
"content-type": "multipart/form-data",
"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')
.content
}
};
// form data
let formData = new FormData();
formData.append("file", this.file);
// send upload request
axios
.post("/store_file", formData, config)
.then(function(response) {
currentObj.success = response.data.success;
currentObj.filename = "";
})
.catch(function(error) {
currentObj.output = error;
});
}
}
};
</script>
That declaration is triggered by your template, where you are binding change event to the method. The whole event as parameter gets passed to the method, Refer this section of Vue docs for better information https://v2.vuejs.org/v2/guide/events.html#Method-Event-Handlers
When a variable is called e it is usually the event. You can always console.log(e) and read its properties in the browser console.
But according to this example e is the file that is uploaded:
methods: {
thumbUrl (file) {
return file.myThumbUrlProperty
},
onFileChange (file) {
// Handle files like:
this.fileUploaded = file
}
}
onFileChange(e) has e as event related to the dom. Since while assigning the function in html if there is no parameter passed, the event as a parameter is automatically passed by javaScript.
The declaration onFileChange(e) {
declares a function with the name onFileChange that takes a single parameter e. That is what introduces the variable into the function body.
Related
I am trying to update the user profile data in my database, but I am stuck at the user profile image. I can't use the v-model for binding, and with v-on:change it doesn't work. This is my code so far, it is working properly, the only issue being the binding.
<template>
-----
<div v-if="!image">
<h2>Select an image</h2>
<input type="file" #change="onFileChange" /> ---->here I would like to use the v-model but can't use it on input type="file"
</div>
<div v-else>
<img :src="image" />
<button #click="removeImage">Remove image</button>
</div>
<input
type="text"
placeholder="Userame"
v-model="user.username"
required
/>
<button
type="button"
class="btn btn-outline-warning waves-effect"
aria-label="Left Align"
#click.prevent="updateProfile(user)"
>
Update profile
</button>
---
</template>
<script>
export default {
data: function () {
return {
user: {},
image: ''
};
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
console.log(file.name);
},
removeImage: function (e) {
this.image = '';
},
updateProfile() {
store
.dispatch("updateProfile", {
username: this.user.username,
email: this.user.email,
profileImage: this.file ------>I need it for the binding here
</script>
You forgot to bind the file to this.file. Update your onFileChange method to this ππ», it will work.
Note: v-model only works with input which use value binding, where input type file doesn't use input value, it makes no sense to use input type file with v-model
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
this.file = files[0]
this.createImage(this.file);
},
I am doing an exercise of an online course. In this exercise I have a form with 3 inputs and I have to extract them to make a request to a server. My problem is that my JavaScript Code only returns the empty string if I log it in the console, not the changed value. I guess it's accessing the inital value of the html. How can I solve this?
JavaScript Code:
// Initial call if the form is submitted
document.querySelector("#compose-submit").onsubmit = send_mail();
// The send_mail function:
function send_mail() {
let recipients = document.querySelector('#compose-recipients').value; // Those return the empty string,
let subject = document.querySelector("#compose-subject").value; // although something was written
let body = document.querySelector("#compose-body").value; // inside
fetch("/emails", {
method: "POST",
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body
})
})
.then(response => response.json())
.then(result => {
console.log(result);
});
return false;
Corresponding html:
<h3>New Email</h3>
<form id="compose-form">
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="submit" class="btn btn-primary" id="compose-submit"/>
</form>
In the first line when you are assigning a callback to the onsubmit event, you need to just pass the function name and not call it.
So, changing your first line of code to
document.querySelector("#compose-submit").onclick = send_mail;
or
bind your event to the form element to make it work with onsumbit event
document.querySelector("#compose-form").onsubmit = send_mail;
should work.
Here's a JSFiddle as a sample (check console)
Change your input type to button to prevent reloading the page after submitting. And you will keep your values
// Initial call if the form is submitted
document.querySelector("#compose-submit").addEventListener('click', () => {
send_mail();
});
// The send_mail function:
function send_mail() {
let recipients = document.querySelector('#compose-recipients').value; // Those return the empty string,
let subject = document.querySelector("#compose-subject").value; // although something was written
let body = document.querySelector("#compose-body").value; // inside
console.log(recipients);
console.log(subject);
console.log(body);
fetch("/emails", {
method: "POST",
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body
})
})
.then(response => response.json())
.then(result => {
console.log(result);
});
return false;
}
<h3>New Email</h3>
<form id="compose-form">
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="button" value="Submit" class="btn btn-primary" id="compose-submit" />
</form>
It's because of the submit type, when you submit the form, it submits the values of the form to the given url path of your action attribute of the form <form action="path_to_fetch" method="POST"> and then refreshed the page after. So your javascript code can't catch the values of the form.
One solution is to prevent the form to be refreshed and let your javascript code do the fetching method.
so in your js code, do this:
// Initial call if the form is submitted
document.querySelector("#compose-submit").addEventListener("click", send_mail);
// The send_mail function:
function send_mail(e) {
let recipients = document.querySelector('#compose-recipients').value; // Those return the empty string,
let subject = document.querySelector("#compose-subject").value; // although something was written
let body = document.querySelector("#compose-body").value; // inside
fetch("/emails", {
method: "POST",
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body
})
})
.then(response => response.json())
.then(result => {
console.log(result);
}).finally(() => {
document.querySelector('#compose-recipients').value = "";
document.querySelector("#compose-subject").value = "";
document.querySelector("#compose-body").value = "";
})
}
Use the finally function to empty the form after submitting the form.
EDIT:
And also change your button type to just button, using the submit type will cause the refresh.
<button class="btn btn-primary" id="compose-submit" type="button">Submit</button>
My html code is
I also need to add sez which is in array format and also i need to add multiple images, need to provide add image and when clicking on it, need to add images as needed by the client
<form method="POST" enctype="multipart/form-data" v-on:submit.prevent="handleSubmit($event);">
<div class="row">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Name</label>
<input type="text" class="form-control" v-model="name">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Alias</label>
<input type="text" class="form-control" v-model="alias">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Sex</label>
<select class="form-control" v-model="sex" id="level">
<option value="Male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
</div>
<div class="row" v-for="(book, index) in sez" :key="index">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Date </label>
<input type="date" class="form-control" v-model="book.date">
</div>
</div>
<div class="col-md-8">
<div class="form-group label-floating">
<label class="control-label"> Details</label>
<input type="text" class="form-control" book.details>
</div>
</div>
</div>
<a #click="addNewRow">Add</a>
<div class="card-content">
<div class="row">
<div class="col-md-4">
<div class="button success expand radius">
<span id="save_image_titlebar_logo_live">Signature</span>
<label class="custom-file-upload"><input type="file" name="photo" accept="image/*" />
</label>
</div>
</div>
<div class="col-md-4">
<div class="button success expand radius">
<span id="save_image_titlebar_logo_live">Recent Photograph</span>
<label class="custom-file-upload">
<input type="file" name="sign"/>
</label>
</div>
</div>
</div>
</div>
</form>
My vue js code is
addForm = new Vue({
el: "#addForm",
data: {
name: '',
alias: '',
sex: '',
sez: [{
date: null,
details: null,
}, ],
photo: '',
sign: '',
},
methods: {
addNewRow: function() {
this.seziure.push({
date: null,
details: null,
});
},
handleSubmit: function(e) {
var vm = this;
data = {};
data['sez'] = this.sez;
data['name'] = this.name;
data['alias'] = this.alias;
data['sex'] = this.sex;
//how to add images
$.ajax({
url: 'http://localhost:4000/save/',
data: data,
type: 'POST',
dataType: 'json',
success: function(e) {
if (e.status) {
vm.response = e;
alert("success")
} else {
vm.response = e;
console.log(vm.response);
alert("Registration Failed")
}
}
});
return false;
},
},
});
This is my code. I have no idea about how to add images in this case.
Can anyone please help me pass this data.
How to pass this data along with images to the backend?
I don't want to use base64 encoding. I need to just pass this image in this ajax post request along with other data
Using axios:
Template
...
<input type="file" name="photo" accept="image/*" #change="setPhotoFiles($event.target.name, $event.target.files) />
...
Code
data () {
return {
...
photoFiles: [],
...
}
},
...
methods: {
...
setPhotoFiles (fieldName, fileList) {
this.photoFiles = fileList;
},
...
handleSubmit (e) {
const formData = new FormData();
formData.append('name', this.name);
formData.append('alias', this.alias);
formData.append('sex', this.sex);
...
this.photoFiles.forEach((element, index, array) => {
formData.append('photo-' + index, element);
});
axios.post("http://localhost:4000/save/", formData)
.then(function (result) {
console.log(result);
...
}, function (error) {
console.log(error);
...
});
}
}
I'm not sure where would you like the extra images to appear, but I added them after this column:
<div class="col-md-4">
<div class="button success expand radius">
<span id="save_image_titlebar_logo_live">Recent Photograph</span>
<label class="custom-file-upload">
<input type="file" name="sign"/>
</label>
</div>
</div>
And here's the column I added β "add images": (You can try this feature here, with the updates)
<div class="col-md-4">
<ul class="list-group" :if="images.length">
<li class="list-group-item" v-for="(f, index) in images" :key="index">
<button class="close" #click.prevent="removeImage(index, $event)">Γ</button>
<div class="button success expand radius">
<label class="custom-file-upload">
<input type="file" class="images[]" accept="image/*" #change="previewImage(index, $event)">
</label>
</div>
<div :class="'images[' + index + ']-preview image-preview'"></div>
</li>
</ul>
<button class="btn btn-link add-image" #click.prevent="addNewImage">Add Image</button>
</div>
And the full Vue JS code (with jQuery.ajax()):
addForm = new Vue({
el: "#addForm",
data: {
name: '',
alias: '',
sex: '',
sez: [{
date: null,
details: null
}],
// I removed `photo` and `sign` because (I think) the're not necessary.
// Add I added `images` so that we could easily add new images via Vue.
images: [],
maxImages: 5,
// Selector for the "Add Image" button. Try using (or you should use) ID
// instead; e.g. `button#add-image`. But it has to be a `button` element.
addImage: 'button.add-image'
},
methods: {
addNewRow: function() {
// I changed to `this.sez.push` because `this.seziure` is `undefined`.
this.sez.push({
date: null,
details: null
});
},
addNewImage: function(e) {
var n = this.maxImages || -1;
if (n && this.images.length < n) {
this.images.push('');
}
this.checkImages();
},
removeImage: function(index) {
this.images.splice(index, 1);
this.checkImages();
},
checkImages: function() {
var n = this.maxImages || -1;
if (n && this.images.length >= n) {
$(this.addImage, this.el).prop('disabled', true); // Disables the button.
} else {
$(this.addImage, this.el).prop('disabled', false); // Enables the button.
}
},
previewImage: function(index, e) {
var r = new FileReader(),
f = e.target.files[0];
r.addEventListener('load', function() {
$('[class~="images[' + index + ']-preview"]', this.el).html(
'<img src="' + r.result + '" class="thumbnail img-responsive">'
);
}, false);
if (f) {
r.readAsDataURL(f);
}
},
handleSubmit: function(e) {
var vm = this;
var data = new FormData(e.target);
data.append('sez', this.sez);
data.append('name', this.name);
data.append('alias', this.alias);
data.append('sex', this.sex);
// The `data` already contain the Signature and Recent Photograph images.
// Here we add the extra images as an array.
$('[class~="images[]"]', this.el).each(function(i) {
if (i > vm.maxImages - 1) {
return; // Max images reached.
}
data.append('images[' + i + ']', this.files[0]);
});
$.ajax({
url: 'http://localhost:4000/save/',
data: data,
type: 'POST',
dataType: 'json',
success: function(e) {
if (e.status) {
vm.response = e;
alert("success");
} else {
vm.response = e;
console.log(vm.response);
alert("Registration Failed");
}
},
cache: false,
contentType: false,
processData: false
});
return false;
},
},
});
Additional Notes
I know you're using Node.js in the back-end; however, I should mention that in PHP, the $_FILES variable would contain all the images (so long as the fields name are properly set); and I suppose Node.js has a similar variable or way of getting the files.
And in the following input, you may have forgotten to wrap book.details in v-model:
<input type="text" class="form-control" book.details>
<input type="text" class="form-control" v-model="book.details"> <!-- Correct -->
UPDATE
Added feature to limit number of images allowed to be selected/uploaded, and added preview for selected image. Plus the "send images as array" fix.
If you're using HTML5, try with a FormData object ; it will encode your file input content :
var myForm = document.getElementById('addForm');
formData = new FormData(myForm);
data: formData
Use below templete to show/upload the image:
<div v-if="!image">
<h2>Select an image</h2>
<input type="file" #change="onImageUpload">
</div>
<div v-else>
<img :src="image" />
<button #click="removeImage">Remove image</button>
</div>
Js code:
data: {
image: '',
imageBuff: ''
},
methods: {
onImageUpload(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
this.imageBuff = file;
reader.onload = (e) => {
this.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function(e) {
this.image = '';
},
handleSubmit(e) {
const formData = new FormData();
formData.append('name', this.name);
formData.append('alias', this.alias);
formData.append('sex', this.sex);
formData.append('image', this.imageBuff);
...
// Ajax or Axios can be used
$.ajax({
url: 'http://localhost:4000/save/',
data: formData,
processData: false, // prevent jQuery from automatically transforming the data into a query string.
contentType: false,
type: 'POST',
success: function(data) {
console.log(data);
...
}
});
}
}
I'm trying to add an input with file upload to my application.
This is my view with two inputs, one text and one file:
<template>
<form class="form-horizontal" submit.delegate="doImport()">
<div class="form-group">
<label for="inputLangName" class="col-sm-2 control-label">Language key</label>
<div class="col-sm-10">
<input type="text" value.bind="languageKey" class="form-control" id="inputLangName" placeholder="Language key">
</div>
</div>
<div class="form-group">
<label for="inputFile" class="col-sm-2 control-label">Upload file</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="inputFile" accept=".xlsx" files.bind="files">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Do import</button>
</div>
</div>
</form>
</template>
In my webapi I have this code which I copied and pasted from here:
public class ImportLanguageController : ApiController
{
public async Task<HttpResponseMessage> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
//Trace.WriteLine(file.Headers.ContentDisposition.FileName);
//Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
At last I have my view model in Aurelia:
import {inject} from 'aurelia-framework';
import {HttpClient, json} from 'aurelia-fetch-client';
#inject(HttpClient)
export class Import {
languageKey = null;
files = null;
constructor(http){
http.configure(config => {
config
.useStandardConfiguration();
});
this.http = http;
}
doImport() {
//What goes here??
}
}
So my question is, what logic goes in my function doImport? I'm not sure the code in my controller method in the webapi is correct, feel free to have comments on that.
This should help you get started:
doImport() {
var form = new FormData()
form.append('language', this.languageKey)
form.append('file', this.files)
//Edit, try this if the first line dont work for you
//form.append('file', this.files[0])
this.http.fetch('YOUR_URL', {
method: 'post',
body: form
})
.then( response => {
// do whatever here
});
}
Depending on the webapi response you provide (if any) you may want to use following:
.then( response => response.json() )
.then( response => {
// do whatever here
});
One thing I should mention too is that fetch uses COR so if you get any CORS error you may need to enable them on the server side.
Here's a gist.run for the Aurelia part (posting won't work unless you change the URL):
https://gist.run/?id=6aa96b19bb75f727271fb061a260f945
I'm really stuck on how I would work with submitting a form that makes an ajax request using Vue.js and vue-resource then using the response to fill a div.
I do this from project to project with js/jQuery like this:
view in blade
{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
<div class="form-group">
<input type="text" name="id" class="form-control" placeholder="id" required="required">
</div>
<button type="submit" class="btn btn-default">Search</button>
{!! Form::close() !!}
js/jquery
var $searchForm = $('#searchForm');
var $searchResult = $('#searchResult');
$searchForm.submit(function(e) {
e.preventDefault() ;
$.get(
$searchForm.attr('action'),
$searchForm.serialize(),
function(data) {
$searchResult.html(data['status']);
}
);
});
What I've done/tried so far in Vue.js:
view in blade
{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
<div class="form-group">
<input type="text" name="id" class="form-control" placeholder="id" required="required">
</div>
<button type="submit" class="btn btn-default" v-on="click: search">Search</button>
{!! Form::close() !!}
vue/js
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
new Vue({
el: '#someId',
data: {
},
methods: {
search: function(e) {
e.preventDefault();
var req = this.$http.get(
// ???, // url
// ???, // data
function (data, status, request) {
console.log(data);
}
);
}
}
});
I'm wondering if it's possible to use components when dealing with the response to output the response data to a div?
Just to summarise everything:
How do I submit a form using vue js and vue-resource instead of my usual jQuery way?
Using a response from ajax, how can I output data into a div preferably using components?
I used this approach and worked like a charm:
event.preventDefault();
let formData = new FormData(event.target);
formData.forEach((key, value) => console.log(value, key));
In order to get the value from input you have to use v-model Directive
1. Blade View
<div id="app">
<form v-on="submit: search">
<div class="form-group">
<input type="text" v-model="id" class="form-control" placeholder="id" required="required">
</div>
<input type="submit" class="btn btn-default" value="Search">
</form>
</div>
<script type="text/javascript">
// get route url with blade
var url = "{{route('formRoute')}}";
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
var app = new Vue({
el: '#app',
data: {
id: '',
response: null
},
methods: {
search: function(event) {
event.preventDefault();
var payload = {id: this.id};
// send get request
this.$http.get(url, payload, function (data, status, request) {
// set data on vm
this.response = data;
}).error(function (data, status, request) {
// handle error
});
}
}
});
</script>
If you want to pass data to component the use 'props' see docs for more info
http://vuejs.org/guide/components.html#Passing_Data_with_Props
If you want use laravel and vuejs together, then checkout
https://laracasts.com/series/learning-vuejs
Add v-model="id" on your text input
then add it to your data object
new Vue({
el: '#someId',
data: {
id: ''
},
methods: {
search: function(e) {
e.preventDefault();
var req = this.$http.get(
'/api/search?id=' + this.id,
function (data, status, request) {
console.log(data);
}
);
}
}
});
Itβs better to remove v-on="click: search" and add v-on="submit: search" on the form tag.
You should add method="GET" on your form.
Make sure you have #someId in your html markup.