使用nodejs进行文件上传进度并表达

时间:2018-03-28 08:21:23

标签: javascript node.js file express upload

我正在尝试使用express-fileupload NPM软件包创建一个Node.js文件上传器。一切正常,但我试图找到一种方法来监控已上传的数据量,以便我可以制作进度条。除了一种方法可以看到已经完成的与文件大小进行比较之外,我有大部分内容。这是我正在处理的GitHub仓库的链接,我将发布代码。 https://github.com/dambergn/nodejs-file-upload

服务器

'use strict';

const fs = require('fs');
const express = require('express');
const fileUpload = require('express-fileupload');
const PORT = process.env.PORT || 3000;
const app = express();

// default options
app.use(fileUpload());

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/public/index.html');
});

// creates upload directory if it does not exist.
let dir = './uploads';
if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}

// express-fileupload application.
app.post('/upload', function (req, res) {
    if (!req.files)
        return res.status(400).send('No files were uploaded.');

    // The name of the input field (i.e "sampleFile") is used to retrieve the uploaded file.
    let sampleFile = req.files.sampleFile;

    // use the mv() method to place the file somewhere on your server.
    sampleFile.mv(`./uploads/${sampleFile.name}`, function (err) {
        console.log(sampleFile);
        if (err)
            return res.status(500).send(err);

        // checks the file size
        let stats = fs.statSync(`./uploads/${sampleFile.name}`);
        let fileSizeInBytes = stats.size;

        // res.send(`${sampleFile.name} Uploaded!  ${fileSizeInBytes} Bytes`);
        res.sendFile(__dirname + '/public/index.html');
    });
});

// Starts the server.
app.listen(PORT, () => {
    console.log('Listening on port:', PORT, 'use CTRL+C to close.');
});

客户端

    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!-- <script src="assets/js/lib/jquery-3.3.1.min.js"></script> -->
    <title>Upload</title>
</head>

<body>
    <h1>Upload</h1>
    <form ref="uploadForm" id="uploadForm" action="http://localhost:3000/upload" method="POST" encType="multipart/form-data">
        <input type="file" name="sampleFile" />
        <br>
        <input type="submit" value="Upload!" action="uploadComplete();"/>
        <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
        <h3 id="status"></h3>
        <p id="loaded_n_total"></p>
    </form>
    <div>
        <ul id="fileInfo">
        </ul>
    </div>

    <script type="text/javascript">
        fileSize = 0;
        fileSymb = '';
        uploadProgress = 0;
        $('#uploadForm').bind('change', function () {
            // clear file info when new file is selected
            document.getElementById("fileInfo").innerHTML = "";
            // gets file information
            let uploadFileName = this[0].files[0].name;
            let uploadFileSize = this[0].files[0].size;
            let uploadFileType = this[0].files[0].type;
            let uploadFileModified = this[0].files[0].lastModifiedDate;
            // console.log(uploadFileName);
            // console.log(uploadFileSize);
            // console.log(uploadFileType);
            // console.log(uploadFileModified);

            function precisionRound(number, precision) {
                var factor = Math.pow(10, precision);
                return Math.round(number * factor) / factor;
            }

            sizes = [Math.pow(1024, 6), Math.pow(1024, 5), Math.pow(1024, 4), Math.pow(1024, 3), Math.pow(1024, 2), 1024];
            symbols = ['PB', 'TB', 'GB', 'MB', 'KB', 'B'];
            for (let j = 0; j <= sizes.length; j++) {
                // debugger;
                if (uploadFileSize <= sizes[j]) {
                    fileSymb = symbols[j];
                    // console.log(fileSymb);
                };
                if (uploadFileSize >= sizes[j]) {
                    fileSize = precisionRound(uploadFileSize / sizes[j], 2);
                    // console.log(uploadFileSize / sizes[j]);
                    // console.log(fileSize);
                    break;
                };
            };

            let fileInfo = [
                `File Name: ${uploadFileName}`,
                `File Size: ${fileSize} ${fileSymb}`,
                `File Type: ${uploadFileType}`,
                `Last Modified: ${uploadFileModified}`
            ];

            for (let i = 0; i < fileInfo.length; i++) {
                let liEm = document.createElement("li");
                let info = document.createTextNode(fileInfo[i]);
                liEm.appendChild(info);
                document.getElementById("fileInfo").appendChild(liEm);
            };

            // document.getElementById("progressBar").value = "75";
        });
        function uploadComplete() {
                document.getElementById("fileInfo").innerHTML = "";
                let liEm = document.createElement("li");
                let info = document.createTextNode("Upload Complete!");
                liEm.appendChild(info);
                document.getElementById("fileInfo").appendChild(liEm);
            };
    </script>
</body>

</html>

任何正确方向的提示或推动都将受到赞赏。

0 个答案:

没有答案