Home > Web Front-end > JS Tutorial > How to implement file upload function with progress bar in JavaScript?

How to implement file upload function with progress bar in JavaScript?

WBOY
Release: 2023-10-21 10:07:47
Original
759 people have browsed it

JavaScript 如何实现带进度条的文件上传功能?

JavaScript How to implement the file upload function with a progress bar?

In modern web development, file upload is a common operation. In order to improve the user experience, it is necessary to add a file upload function with a progress bar. This article will introduce how to use JavaScript to implement the file upload function with a progress bar and give specific code examples.

1. Front-end page layout

First, we need to build a layout containing file selection buttons, progress bars and upload buttons on the front-end page.

<!DOCTYPE html>
<html>
<head>
    <title>带进度条的文件上传</title>
</head>
<body>
    <h1>带进度条的文件上传</h1>
    <input type="file" id="fileInput">
    <progress id="progressBar" value="0" max="100"></progress>
    <button onclick="uploadFile()">上传</button>
</body>
</html>
Copy after login

In the above code, we use the element to create a file selection button, the element to create a progress bar, and an element to trigger the upload Action button.

2. JavaScript implements the upload function

Next, we use JavaScript to implement the file upload function and update the progress bar in real time during the upload process.

function uploadFile() {
    var fileInput = document.getElementById("fileInput");
    var file = fileInput.files[0];
    
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/upload", true);

    xhr.upload.addEventListener("progress", function(e) {
        if (e.lengthComputable) {
            var percentComplete = Math.round((e.loaded / e.total) * 100);
            var progressBar = document.getElementById("progressBar");
            progressBar.value = percentComplete;
        }
    }, false);

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log("上传完成");
        }
    };

    xhr.send(file);
}
Copy after login

In the above code, we first get the element of the file selection button and get the selected file. We then create an XMLHttpRequest object and specify the URL for the POST request. Here, you need to change it to your own backend interface address according to the actual situation.

Next, we listen to the progress event during the upload process, calculate the upload percentage, and update the value of the progress bar every time the progress is updated.

When the readyState of the request changes to 4 (the request is completed) and the status is 200 (the request is successful), we can determine that the file upload has been completed.

3. Back-end processing of file upload

The above code only handles the file upload logic of the front-end, and corresponding processing needs to be performed on the back-end. Here we take Node.js as an example, using the Express framework to handle file upload requests and save the files to the server.

const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), function (req, res, next) {
    // 文件上传成功后的处理逻辑
    console.log(req.file);
});
Copy after login

In this code, we first introduce the Express and multer modules, and use the multer middleware to handle file upload requests. multer configures the target directory for file upload to be "uploads/", and uses upload.single('file') to receive a file named "file".

After the file is uploaded successfully, the req.file object can be printed out on the console. This object contains relevant information about the uploaded file, such as file name, file size, etc.

4. Summary

Through the above code example, we successfully implemented a file upload function with a progress bar. In the front-end part, JavaScript is used to monitor the progress event during the upload process and update the value of the progress bar in real time. In the backend part, file upload requests are processed through the Express framework and multer middleware, and the files are saved to the server.

If you need to use it in actual projects, please modify the code according to the actual situation. I hope this article can help you implement a fast and convenient file upload function.

The above is the detailed content of How to implement file upload function with progress bar in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template