File upload is one of the basic requirements of the web application.
I am using the Axios package to send AJAX request to upload a file. Send a selected file using the FormData object.
In this tutorial, I show how you can upload a file using Vue.js and PHP.
Contents
1. Download & Include
- Download Axios package from GitHub. or you can also use CDN (https://unpkg.com/axios/dist/axios.min.js).
- Now, include
axios.min.js
withvue.js
in the<head>
section.
<script src="vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2. HTML
Create a file element and a button in the <div id='myapp'>
.
In the file element added ref='file'
which use to get the selected file in Vue script.
Add @click
event on the button which calls uploadFile()
method.
Completed Code
<div id='myapp'> <input type="file" id="file" ref="file" /> <button type="button" @click='uploadFile()' >Upload file</button> </div>
3. PHP
Create an ajaxfile.php
file and uploads
directory for storing the files.
Assign valid file extensions in $valid_extensions
Array and get the file extension from the file.
Upload the file if a file extension is found in $valid_extension
Array and return 1
otherwise 0
.
Completed Code
<?php // File name $filename = $_FILES['file']['name']; // Valid file extensions $valid_extensions = array("jpg","jpeg","png","pdf"); // File extension $extension = pathinfo($filename, PATHINFO_EXTENSION); // Check extension if(in_array(strtolower($extension),$valid_extensions) ) { // Upload file if(move_uploaded_file($_FILES['file']['tmp_name'], "uploads/".$filename)){ echo 1; }else{ echo 0; } }else{ echo 0; } exit;
4. Script
Initialize Vue on #myapp
.
Add file
data variable and define uploadFile()
method which gets called on the upload button click.
Select the file and append in FormData
object.
Send POST request to ajaxfile.php
and pass formData
as data.
Also, set Content-Type: 'multipart/form-data'
in header.
On successful callback if response.data
is 0
then alert('File not uploaded.')
otherwise, alert('File uploaded successfully.')
.
Completed Code
var app = new Vue({ el: '#myapp', data: { file: "", }, methods: { uploadFile: function(){ this.file = this.$refs.file.files[0]; let formData = new FormData(); formData.append('file', this.file); axios.post('ajaxfile.php', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(function (response) { if(!response.data){ alert('File not uploaded.'); }else{ alert('File uploaded successfully.'); } }) .catch(function (error) { console.log(error); }); } } })
5. Output
6. Conclusion
You don’t need to create a <form >
to add file element.
You can pass the extra parameter to FormData
object using append()
method which you required for processing in AJAX file.
View this tutorial to know multiple files upload using Vue.js and PHP.
If you found this tutorial helpful then don't forget to share.
Please upload the complete source code of this project to the github
The download link is incorrect.
Thanks for mentioning it. I updated the link.
../uploads/
because is relative path from back-end file “ajaxfile.php”
Thank you
You’re welcome.
How can we update these codes for multi file upload?
Upload other Form Data (Name, age, gender etc.) along with the image file. How to do it in one script? Can you post complete code for the same. (Vue-PHP please)
Hi Pankaj,
Append extra parameter to FormData object. Example – fd.append(‘name’,’user name’);fd.append(‘age’,23);. In PHP read it using POST method, e.g. $name = $_POST[‘name’]; $age = $_POST[‘age’];
Great Thanks a lot
Hi I do everything exactly the same like u did, but I keep getting response 0.
when I console log the response i get:
{data: 0, status: 200, statusText: “OK”, headers: {…}, config: {…}, …}config: {url: “//my-serv/serv/ajaxfile1.php”, method: “post”, data: FormData, etc,
but like u see data is 0 I run out of ideas what it cold cause it
Have you checked the file extension which you are uploading is defined in $valid_extensions Array and folder permission where you are uploading files?