Using Http to Upload Files From Webkitdirectory
A Complete Guide to File Uploading in JavaScript
Single file, multiple files, drag, and paste, everything yous need to know
File upload is a common function for a web projection. I believe that everyone has encountered related requirements more or less during the development.
In this article, I have summarized some scenarios and solutions, hoping to assist you thoroughly grasp questions related to file uploading.
Our Goals
First, let'due south analyze the specific functions of file uploading.
According to upload target, there are 3 kind tasks:
- Upload a single file
- Upload multiple files at the same time
- Upload the entire folder
Co-ordinate to the user deportment, in that location are:
- Cull a file the upload
- Drag the file to the box then upload
- Upload from clipboard
From a performance perspective, nosotros may demand:
- Upload after compressing a file
- Divide a big file into blocks then uploading
And additionally, sometimes we may not upload files in the client browser, merely through the server to upload to another server.
We will discuss these in turn.
Prerequisites
Before the start coding, we notwithstanding need to understand some groundwork noesis.
Outset, when uploading files, nosotros apply Axios, the most popular HTTP Library. In actual development, we generally don't use XMLHttpRequest directly, and using Axios conforms to the real development model.
When we discuss 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 you lot volition have a brief understanding of formdata, we use this data format to upload files.
Upload a unmarried file
The demand to upload a file is too common. For instance, when you register for Medium, you demand to upload an avatar.
The file upload function requires cooperation between 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 complete process of file uploading:
- User selects a file in the browser
- User click the upload push 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 Lawmaking
All the code of this project was held on GitHub:
You can clone information technology to your estimator:
# clone it
$ git clone git@github.com:BytefishMedium/FileUploading.git # and install npm bundle
$ cd FileUloading
$ npm install
All the code related to single file uploading was put on 1-SingleFile
folder.
-
client.html
related to client-side code. -
server.js
related to server-side code
To run the server, you can get to the folder and run this control:
$ node server.js
And so you can open up client.html
on any browser.
The specific operation I have shown in the gif above. You can effort it for yourself beginning, and then read on.
Client-side lawmaking
Um, How many steps does it take to put a giraffe into a refrigerator?
Merely three steps:
- Open up the door
- put the giraffe in
- and close the door.
The same is truthful for uploading files, we only demand three steps:
- Let users choose a file to upload
- Read this file
- Upload the file using Axios
In HTML, we can use the input
element. Just set up the type of this element to file
, then the element can be used to select the file.
<input id="fileInput" type="file"/>
After 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") console.log(uploadFileEle.files[0]);
Finally, we employ Axios' mail service method to upload files. But before uploading the file, we also need to package this file into FormData format.
permit file = fileElement.files[0];
let formData = new FormData();
formData.gear up('file', file); axios.mail("http://localhost:3001/upload-single-file", formData)
.then(res => {
console.log(res)
})
Tips: FormData is a key-value type information format. Here is an case:
Well, these are the noesis points related to file uploading. The more consummate code is as follows:
This code is actually to implement the three steps we said before:
It'due south merely that we added two additional functions:
- One is the upload push button. When the user clicks the upload button, nosotros beginning executing the upload logic.
- And then we accept one more judgment to ensure that the user really selects a file.
And then, when Axios uploads a file, information technology allows us to monitor the progress of the file uploading.
We know that HTTP is built on peak of TCP. If an HTTP packet is relatively large, information technology may be decomposed into multiple different TCP packets for transmissions in the network.
If yous need to write a progress bar to evidence the user the progress of the uploading, you can use this API.
axios.mail("http://localhost:3001/upload-single-file", formData, {
onUploadProgress: (progressEvent) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.full
);
panel.log(`upload process: ${percentCompleted}%`);
},
});
progressEvent.loaded
ways how many bytes have upload success and progressEvent.total
means total bytes of the file.
Ok, this is our client-side code.
Server-side code
To start a server, we can use Koa. Here is a tiny server using Koa:
This is the most basic Koa demo. Since this article focuses on file uploading, then I volition not explain this in detail. If you don't familiar with this, you can read the official documentation.
- Koa
- Koa-router
Our client uses the format of FormData to upload files, so our server as well needs to parse FormData. And Koa-multer is a middleware that helps united states parse FormData information:
About Koa-multer, yous can read their official documentation:
- Koa-multer
- Multer
The key lawmaking is uoload.single('file')
, this line of code can assistance us parse the information of FormData, and then put the corresponding information in the ctx.request.file
.
In fact, at this time, our server can already receive the files uploaded by the client, just information technology does non store them to the disk after receiving the files.
If nosotros want Koa-multer to salvage the file to disk for u.s., we can add the following configuration:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(naught, UPLOAD_DIR);
},
filename: part (req, file, cb) {
cb(nada, `${file.originalname}`);
},
});
const upload = multer({ storage: storage });
The consummate code is server.js
, and you lot can read it directly in the code repository.
The current period chart looks similar this:
Anyway, you should try it yourself.
Upload multiple files
With the above foundation, it is much simpler for us to write the code for uploading multiple files.
First, nosotros need to change the input
chemical element and add the multiple
attribute to it.
<input blazon="file" id="fileInput" multiple>
This is to tell the browser that now this input
element should allow the user to select multiple files at the same time.
Then later on the user selects multiple files, the information will be placed in fileElement.files
. When we construct formdata
, we need to traverse this listing and put all files into formdata
.
let files = Array.from(fileElement.files); let formData = new FormData();
files.forEach((file) => {
formData.append("file", file);
});
And so the lawmaking of uploading the file doesn't demand modification.
Here is the complete lawmaking:
The file is located on two-MultipleFiles/client.html
in the project.
At the same time, nosotros too need to arrange the code on the server-side.
Kickoff, we demand to add the respective route /upload-multiple-files
, and then use the upload.fields([{ name: "file" }])
middleware to handle multiple files. Subsequently that, the FormData information in request
will exist placed in ctx.files.file
.
Demo:
Upload directory
At present allow's look at the steps to upload a directory.
Similarly to earlier, we need to prepare the aspect of the input
element to this:
<input type="file" id="fileInput" webkitdirectory>
Then when uploading the directory, the files
object of input element will accept the webkitRlativePath
property, and we will also add them to the formdata
It should exist noted here that when the file name contains \
, koa-multer may make an error. To fix this, we need to replace \
with @
symbol.
formData.append('file', file, file.webkitRelativePath.replace(/\//g, "@"));
So we as well need to modify the corresponding server code:
Demo:
Conclusion
Well, we have analyzed the process of uploading a unmarried file, multiple files, and directories in plow. Information technology's actually very simple, simply 3 steps:
- Using the
input
chemical element to permit the user select a file - Read the file and construct FormData
- Upload FormData with Axios
All the code is on GitHub, you tin can try it yourself. If you lot have whatever questions, you lot can leave a annotate.
Due to the length of the article, the rest of the file uploading will be included in a subsequently commodity. If you are interested in this content, you tin follow me.
Thanks for reading.
Source: https://betterprogramming.pub/a-complete-guide-of-file-uploading-in-javascript-2c29c61336f5
0 Response to "Using Http to Upload Files From Webkitdirectory"
Post a Comment