James Ellis

James Ellis

1559269295

Uploading Files and Images With Vue and Express

I am pretty sure you must have googled this before:

How to upload images using Node.js?

How to validate uploaded files using Node.js?

File uploading using MERN stack

If you haven’t, I can assure you that in future you will. Files are an important part of the web ecosystem.

Dread it. Run from it. File uploading still arrives.

Ahh, okay. This post is about uploading images using Express and a popular frontend framework called Vue. I choose Vue because I think it’s underrated and under-appreciated because of the popularity of both Angular and React, and there exists already a bunch of tutorials for everything on React and Angular. Yep, You can say I have a soft corner for the underdogs ❤.

And the reason for choosing Express is because I don’t have experience with any other Node.js frameworks🤐.

We will not only focus on uploading the files but also make sure the uploaded files are correct (people like calling it, Validation). I’ll not consume more of your time with this intro and will get straight to the point.

Let’s hop into this tutorial🤩.

Material-UI components with Bit: Share, choose, use

Creating the form

We will be using Vue CLI, so if you have not installed it then do install it.

npm i -g @vue/cli
#OR
yarn global add @vue/cli

Now we need to create the project:

vue create vue-uploader

Once done, we have to start our Vue application using,

cd vue-uploader
yarn serve

The first thing to do is to create a component that is responsible for all the file uploading. Create a file FileUpload.vue in the components directory and drop the following code in the file.

<template>
<div class="file">
</div>
</template>
<script>
export default {
  name: 'FileUpload'
}
</script>

Next obvious step is to include this component into your App component,

App.vue

Good, nothing more to be added to the App.vue file. We will focus and concern ourselves only with FileUpload component. We need to create an input form for our user so that they can upload the file.

The static form would look something like this:-

FileUpload.vue

So, if you visit localhost:8080 you would see a form which allows you to input the file. But it doesn’t do anything. You submit the file but nothing happens. So what to do?

We should get the file entered by our user and store it inside the component’s data property and then make an ajax post request to the server with the file data.

We will be using axios for making our request to the backend.

yarn add axios
# OR 
npm i axios 

We will use the ‘onChange’ event handler on the input field to get the file. We will be using refs to get the current file at that moment. And use the onSubmit event handler for making the post request with the file.

FileUpload.vue

We will get the file using _this.$refs.file_. The onChange event will run once the file is selected, and the onSelect method is called which gets the file and stores in the file data property. On the submit button click, the onSubmit method is fired which gets the file and makes a post request (thanks to axios) using async-await.

Will use the message data to display the message based on the status of the response from the server.

Ohkayy, everything makes sense but what is this FormData?

The [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) object lets you compile a set of key/value pairs to send using [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest). It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.

Now we have to set up our backend API, to store our files on the server.

Setting up the backend

We create another directory and dive into the terminal and type:

npm init

Just fill in the details asked by npm or ignore them (suit yourself). Once we are done with this create a file named index.js. This script is the one where all of our code goes in.

We will add express and cors as dependencies:

npm i express cors

We will use nodemon so if you have it set up then no worries else run a simple command and you are all set.

npm i -g nodemon

The package.json should look like this:

FileUpload.vue

Time to write some code in index.js and set up our server.

index.js

Run npm start and spin up the server.

Not very useful for file uploading. True, and here comes Multer to the rescue.

Multer

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

Installation

npm i multer

Once we are done with the installation, time to write some code for file handling on the server side.

index.js

Multer adds a body object and a file or files object to the request object. The bodyobject contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.

The file key in upload.single should match with ‘FormData’ key in the Vue component.

After the successful request, you will notice that there exists a directory upload with the uploaded files.

Woohoo!!!. Uploaded the files successfully on the server.

But we need one more thing, Validation. We don’t want our users to upload the wrong type of files or incorrect files, we want them to upload the files which meet certain criteria. We will be heading towards the validation both on server and client side.

Server-Side Validation

Two things we will be validating:-

  • Type of file
  • Size of file

Type of file

Let’s say, we only accept images. We want the uploaded file to have an extension of _.png_, _.jpeg_, and _.jpg_. We validate the files on the basis of their extension.

const upload = multer({
  dest: './uploads',
  fileFilter
});

If the file’s mimetype, doesn’t exist in our allowedTypes array then we create an error object and return that error with an error code attached to it.

Now the next thing is to catch this error and handle it. We will be creating a middleware to handle this situation by sending an error response on the client side -

fileFilter function

Size of file

Our users should not be able to enter a file of any size. We need to set a certain size limit for the valid files.

const upload = multer({
  dest: './uploads',
  fileFilter,
  limits: {
    fileSize: 500000
  }
});

That’s it if the files size increase more than 500KB then an error will be thrown which will be handled by our middleware.

Finally, our index.js will look like this:-

We will use this response error message and display it on the client side.

catch(err){
  this.message = err.response.data.error
}

Client-side Validation

Client-side validation is pretty much simple, once we select the file we can easily check for the file type and size in the onSelect method.

Self-explanatory!! And that sums up the client side validation.

Note: file.type on the client is equivalent to file.mimetype on server

You can check out the complete Github repo here.

Conclusion

In this article, we learned about uploading files on the server using Express and Vue.js. Hope you liked this article and learned something new, and if you did, clap your 💖 out and follow me for more content on Medium and Twitter. Thanks for reading 🙏 Please feel free to comment and ask anything.

Learn more

Curso Avanzado de Vuejs 2, Vuex y AdonisJs 4

VueJS + Firebase: Desde 0 hasta una proyecto en internet

Vuejs 2 y Vuex desde 0 con las mejores prácticas

Secure Your VueJs Applications With Auth0

Crea Sistemas de Compras - Ventas con Laravel 5.7 y VuejS

Desarrolla sistemas Web en ASP Net Core, SQL Server y Vuejs

#vue-js #node-js #express

What is GEEK

Buddha Community

Uploading Files and Images With Vue and Express
Ahebwe  Oscar

Ahebwe Oscar

1620200340

how to integrate CKEditor in Django

how to integrate CKEditor in Django

Welcome to my Blog, in this article we learn about how to integrate CKEditor in Django and inside this, we enable the image upload button to add an image in the blog from local. When I add a CKEditor first time in my project then it was very difficult for me but now I can easily implement it in my project so you can learn and implement CKEditor in your project easily.

how to integrate CKEditor in Django

#django #add image upload in ckeditor #add image upload option ckeditor #ckeditor image upload #ckeditor image upload from local #how to add ckeditor in django #how to add image upload plugin in ckeditor #how to install ckeditor in django #how to integrate ckeditor in django #image upload in ckeditor #image upload option in ckeditor

I am Developer

1597559012

Multiple File Upload in Laravel 7, 6

in this post, i will show you easy steps for multiple file upload in laravel 7, 6.

As well as how to validate file type, size before uploading to database in laravel.

Laravel 7/6 Multiple File Upload

You can easily upload multiple file with validation in laravel application using the following steps:

  1. Download Laravel Fresh New Setup
  2. Setup Database Credentials
  3. Generate Migration & Model For File
  4. Make Route For File uploading
  5. Create File Controller & Methods
  6. Create Multiple File Blade View
  7. Run Development Server

https://www.tutsmake.com/laravel-6-multiple-file-upload-with-validation-example/

#laravel multiple file upload validation #multiple file upload in laravel 7 #multiple file upload in laravel 6 #upload multiple files laravel 7 #upload multiple files in laravel 6 #upload multiple files php laravel

I am Developer

1597499549

Ajax Multiple Image Upload with Progress bar with jQuery in Laravel

In this post, i will show you, how you can upload multiple file with progress bar in laravel using jQuery ajax.

So follow below given steps to create ajax multiple image upload with progress bar with jquery and laravel php.

Multiple File Upload with Progress bar Using jQuery and Laravel PHP

Now follow the below given simple and easy step to upload multiple file with progress bar in laravel using jQuery ajax:

  • Step 1: Download Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Migration & Model
  • Step 4: Add Routes For Multiple File Upload
  • Step 5: Create Controller by Artisan
  • Step 6: Create Blade View
  • Step 7: Run Development Server

https://www.tutsmake.com/laravel-7-multiple-file-upload-with-progress-bar/

#multiple file upload with progress bar using jquery and laravel #laravel multiple file upload ajax with progress bar #how to upload multiple images with progress bar in laravel #laravel 7 multiple image upload example #image upload with progress bar laravel #laravel multiple image upload ajax

I am Developer

1597563325

Laravel 7/6 Image Upload Example Tutorial

Laravel image upload example tutorial. Here, i will show you how to upload image in laravel 7/6 with preview and validation.

Before store image into db and folder, you can validate uploaded image by using laravel validation rules. as well as you can show preview of uploaded image in laravel.

Image Upload In Laravel 7/6 with Validation

Image upload in laravel 7/6 with preview and validation. And storage image into folder and MySQL database by using the below steps:

Install Laravel Fresh App
Setup Database Details
Generate Image Migration & Model
Create Image Upload Route
Create Image Controller
Create Image Upload and Preview Blade View
Start Development Server

https://www.tutsmake.com/laravel-7-6-image-upload-with-preview-validation-tutorial/

#laravel 7 image upload example #laravel upload image to database #how to insert image into database in laravel #laravel upload image to storage #laravel image upload tutorial #image upload in laravel 7/6

I am Developer

1595240610

Laravel 7 File Upload Via API Example From Scratch

Laravel 7 file/image upload via API using postman example tutorial. Here, you will learn how to upload files/images via API using postman in laravel app.

As well as you can upload images via API using postman in laravel apps and also you can upload images via api using ajax in laravel apps.

If you work with laravel apis and want to upload files or images using postman or ajax. And also want to validate files or images before uploading to server via API or ajax in laravel.

So this tutorial will guide you step by step on how to upload file vie API using postman and ajax in laravel with validation.

Laravel Image Upload Via API Using Postman Example

File

Follow the below given following steps and upload file vie apis using postman with validation in laravel apps:

  • Step 1: Install Laravel New App
  • Step 2: Add Database Credentials
  • Step 3: Generate Migration & Model
  • Step 4: Create Routes For File
  • Step 5: Generate Controller by Artisan
  • Step 6: Run Development Server
  • Step 7: Laravel Upload File Via Api Using PostMan

Checkout Full Article here https://www.tutsmake.com/laravel-file-upload-via-api-example-from-scratch/

#uploading files via laravel api #laravel file upload api using postman #laravel image upload via api #upload image using laravel api #image upload api in laravel validation #laravel send file to api