How to Upload a File Using Javascript
A Complete Guide to File Uploading in JavaScript
Single file, multiple files, drag, and paste, everything you need to know
File upload is a common function for a web project. I believe that everyone has encountered related requirements more or less during the development.
In this article, I take summarized some scenarios and solutions, hoping to help you thoroughly grasp questions related to file uploading.
Our Goals
First, permit'south clarify the specific functions of file uploading.
According to upload target, there are 3 kind tasks:
- Upload a single file
- Upload multiple files at the aforementioned fourth dimension
- Upload the entire folder
According to the user deportment, there are:
- Choose a file the upload
- Drag the file to the box then upload
- Upload from clipboard
From a performance perspective, nosotros may need:
- Upload after compressing a file
- Split up a large file into blocks then uploading
And additionally, sometimes we may not upload files in the client browser, simply through the server to upload to another server.
Nosotros will discuss these in turn.
Prerequisites
Before the start coding, we still need to understand some groundwork knowledge.
Beginning, when uploading files, we use Axios, the most popular HTTP Library. In actual development, nosotros more often than not don't use XMLHttpRequest directly, and using Axios conforms to the existent development model.
When we hash out uploading files in the front-end, if we want to fully understand the relevant principles, we must sympathise the relevant back-end lawmaking. Here we use the Koa to implement our server.
Finally, I hope yous will have a brief understanding of formdata, we use this data format to upload files.
Upload a single file
The demand to upload a file is also mutual. For example, when y'all annals for Medium, y'all need to upload an avatar.
The file upload function requires cooperation betwixt the customer and the server. In our project, the user selects a file in the customer and uploads it to the server; the server saves the file and returns the URL of it.
Here is the project preview:
The above Gif shows the consummate process of file uploading:
- User selects a file in the browser
- User click the upload button
- The uploaded files are placed in the
uploadFiles
folder of the server - Then the server returns a URL, which is the address of the uploaded file
- Users can access the resource through this URL
The Code
All the code of this project was held on GitHub:
You can clone it to your figurer:
# clone information technology
$ git clone git@github.com:BytefishMedium/FileUploading.git # and install npm package
$ cd FileUloading
$ npm install
All the lawmaking related to single file uploading was put on 1-SingleFile
folder.
-
client.html
related to client-side code. -
server.js
related to server-side lawmaking
To run the server, yous tin go to the folder and run this command:
$ node server.js
Then you can open customer.html
on whatever browser.
The specific operation I have shown in the gif above. You can attempt it for yourself first, and and then read on.
Customer-side code
Um, How many steps does information technology take to put a giraffe into a fridge?
Simply 3 steps:
- Open up the door
- put the giraffe in
- and close the door.
The same is true for uploading files, nosotros but need iii steps:
- Let users choose a file to upload
- Read this file
- Upload the file using Axios
In HTML, we tin use the input
element. Only gear up the blazon of this element to file
, then the element can be used to select the file.
<input id="fileInput" type="file"/>
Afterward the user selects a file, the metadata of the file will be stored in the files
property of this input element.
const uploadFileEle = document.getElementById("fileInput") panel.log(uploadFileEle.files[0]);
Finally, we utilise Axios' postal service method to upload files. But before uploading the file, we likewise need to package this file into FormData format.
let file = fileElement.files[0];
let formData = new FormData();
formData.set('file', file); axios.post("http://localhost:3001/upload-unmarried-file", formData)
.and then(res => {
console.log(res)
})
Tips: FormData is a primal-value type information format. Hither is an instance:
Well, these are the knowledge points related to file uploading. The more complete lawmaking is as follows:
This code is actually to implement the three steps nosotros said before:
It's but that we added two additional functions:
- I is the upload button. When the user clicks the upload button, we starting time executing the upload logic.
- Then we take one more judgment to ensure that the user actually selects a file.
Then, when Axios uploads a file, it allows united states to monitor the progress of the file uploading.
We know that HTTP is built on top of TCP. If an HTTP packet is relatively large, it may exist decomposed into multiple different TCP packets for transmissions in the network.
If you need to write a progress bar to show the user the progress of the uploading, you tin use this API.
axios.mail("http://localhost:3001/upload-unmarried-file", formData, {
onUploadProgress: (progressEvent) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
console.log(`upload procedure: ${percentCompleted}%`);
},
});
progressEvent.loaded
means how many bytes have upload success and progressEvent.full
means total bytes of the file.
Ok, this is our customer-side code.
Server-side lawmaking
To start a server, we can apply Koa. Here is a tiny server using Koa:
This is the most basic Koa demo. Since this article focuses on file uploading, so I will not explain this in detail. If you don't familiar with this, y'all can read the official documentation.
- Koa
- Koa-router
Our client uses the format of FormData to upload files, so our server also needs to parse FormData. And Koa-multer is a middleware that helps us parse FormData data:
Near Koa-multer, y'all tin can read their official documentation:
- Koa-multer
- Multer
The key lawmaking is uoload.single('file')
, this line of code tin can help us parse the data of FormData, and so put the corresponding data in the ctx.request.file
.
In fact, at this fourth dimension, our server tin already receive the files uploaded by the client, but it does not shop them to the disk later receiving the files.
If we want Koa-multer to salvage the file to disk for u.s., we tin add the post-obit configuration:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(zippo, UPLOAD_DIR);
},
filename: function (req, file, cb) {
cb(null, `${file.originalname}`);
},
});
const upload = multer({ storage: storage });
The consummate lawmaking is server.js
, and you lot tin can read it directly in the code repository.
The current menses chart looks similar this:
Anyway, you should endeavor it yourself.
Upload multiple files
With the higher up foundation, it is much simpler for us to write the code for uploading multiple files.
First, we demand to modify the input
element and add the multiple
aspect to it.
<input blazon="file" id="fileInput" multiple>
This is to tell the browser that now this input
chemical element should allow the user to select multiple files at the same fourth dimension.
Then after the user selects multiple files, the data volition be placed in fileElement.files
. When we construct formdata
, we demand to traverse this list and put all files into formdata
.
allow files = Array.from(fileElement.files); permit formData = new FormData();
files.forEach((file) => {
formData.append("file", file);
});
And then the code of uploading the file doesn't need modification.
Here is the complete code:
The file is located on ii-MultipleFiles/client.html
in the projection.
At the same fourth dimension, nosotros also need to adjust the code on the server-side.
First, we need to add the corresponding route /upload-multiple-files
, and so use the upload.fields([{ name: "file" }])
middleware to handle multiple files. After that, the FormData data in asking
will be placed in ctx.files.file
.
Demo:
Upload directory
Now let's look at the steps to upload a directory.
Similarly to earlier, we demand to set the attribute of the input
element to this:
<input type="file" id="fileInput" webkitdirectory>
So when uploading the directory, the files
object of input element will take the webkitRlativePath
belongings, and nosotros will also add them to the formdata
Information technology should be noted here that when the file proper noun contains \
, koa-multer may make an error. To set this, we demand to replace \
with @
symbol.
formData.suspend('file', file, file.webkitRelativePath.replace(/\//one thousand, "@"));
Then we as well need to change the corresponding server code:
Demo:
Conclusion
Well, we accept analyzed the procedure of uploading a unmarried file, multiple files, and directories in plough. It's actually very uncomplicated, merely 3 steps:
- Using the
input
element to let the user select a file - Read the file and construct FormData
- Upload FormData with Axios
All the code is on GitHub, you tin try information technology yourself. If you take any questions, you can leave a comment.
Due to the length of the article, the rest of the file uploading will be included in a subsequently article. If you are interested in this content, you can follow me.
Thank you for reading.
Source: https://betterprogramming.pub/a-complete-guide-of-file-uploading-in-javascript-2c29c61336f5
0 Response to "How to Upload a File Using Javascript"
Post a Comment