nodejs 上传 connect-multiparty

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/adley_app/article/details/89404369

目录

├── app.js
├── node_modules
├── package-lock.json
├── package.json
├── public
├──	├── images
├──	├── index.html
├──	└── show.html
└── tmp

前端

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<input type="file" multiple accept='image/*' id="file1">
<button id="btn">提交</button>

<p id="loading">

</p>

<script>

    let loading = document.getElementById('loading');

    document.querySelector('#btn').onclick = function () {

        loading.innerHTML = '正在上传中...'

        let file1 = document.getElementById('file1');
        let files = file1.files;

        let formData = new FormData();
        [].slice.call(files).forEach((value, index) => {
            console.log(value, index);
            formData.append('img' + index, value, value.name);
        });

        let xhr = new XMLHttpRequest();
        xhr.open('POST', '/upload');
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                console.log(xhr.responseText);
                // alert(xhr.responseText)
                loading.innerHTML = xhr.responseText;
            }
        }
        xhr.send(formData);
    }
</script>
</body>
</html>

nodejs 后端

const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const multiparty = require('connect-multiparty');

app.use(express.static('./public'));

const multipartyMiddleware = multiparty({
    uploadDir: './tmp'
});

/**
 * @API
 * @upload
 */
const IMG_PATH = path.resolve('./public/images/');
app.post('/upload', multipartyMiddleware, async (req, res) => {
    
    try {
        let files = req.files;

        for (let item in files) {
            let tmpPath = files[item].path;
            let name = files[item].name;

            let d = new Date();
            let getDate = `${d.getFullYear()}${d.getMonth()+1}${d.getDate()}`;

            let newImgPath = path.resolve(IMG_PATH, `${getDate}_${name}`);
            let result = await RenameFile(tmpPath, newImgPath);

            if (!result) {
                return res.send({
                    errCode: -50000,
                    msg: 'upload error'
                });
            }
        }

        res.send({
            errCode: 0,
            msg: 'upload success'
        });
    } catch (err) {
        return res.send({
            errCode: -50000,
            msg: 'upload error'
        });
    }
});

/**
 * @API
 * @getImgList 
 */
app.get('/getImgList', async (req, res) => {
    let result = await getImgSrc();
    res.send(result);
});


/**
 * @function
 * @RenameFile
 */
function RenameFile(oldPath, newPath) {
    return new Promise((resolve, reject) => {
        fs.rename(oldPath, newPath, (err) => {
            if (err) {
                console.log(err);
                return reject(null);
            }
            resolve(true);
        });
    });
}

/**
 * @function
 * @getImgSrc
 */
function getImgSrc() {
    return new Promise((resolve, reject) => {
        fs.readdir(path.resolve('./public/images'), (err, result) => {
            if (err) {
                return reject(err);
            }
            result = result.map(item => '/images/' + item);
            resolve(result);
        });
    });
}


app.listen(9091, () => {
    console.log(`server is running at 9091 ...`);
});


猜你喜欢

转载自blog.csdn.net/adley_app/article/details/89404369