JQ + Node 实现本地图片上传

参考博客:Node Js 实现图片上传 学习笔记

前台页面 index.html

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

<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
    <style>
        img {
    
    
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>
    <input id="pic" type="file">
    <button id="btn">上传</button>
    <img id="img" src="" alt="">


    <script src="../jquery.js"></script>
    <script>
        $('#btn').on('click', () => {
    
    
            let myform = new FormData();
            myform.append('file', $('#pic')[0].files[0]);
            $.ajax({
    
    
                url: "http://localhost:8888/upload",
                type: "post",
                data: myform,
                contentType: false,
                processData: false, //不将传输数据序列化
                success: function (data) {
    
    
                    console.log(data);
                    $('#img').attr('src', data.url);
                },
                error: function (data) {
    
    
                    console.log(data)
                }
            });
        })
    </script>
</body>

</html>

后台页面 myNode.js
用node写后台,需要安装 express 和 formidable 两个模块

// 导入必备的模块
let express = require('express');
let router = express.Router();
let formidable = require('formidable');
let fs = require('fs');
let app = express();

//设置跨域
app.all('*', function (req, res, next) {
    
    
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
})

router.get('/', function (req, res) {
    
    
    res.send({
    
     title: '首页' });
});

router.post('/upload', function (req, res) {
    
    
    //创建上传表单
    let form = new formidable.IncomingForm();

    //设置编辑
    form.encoding = 'utf-8';

    //设置上传目录(判断有没有文件夹,没有就同步创建文件夹)
    if (fs.existsSync('./img')) {
    
    
        form.uploadDir = './img/';
    } else {
    
    
        fs.mkdirSync('./img');
        form.uploadDir = './img/';
    }

    //保留后缀
    form.keepExtensions = true;

    //文件大小 2M
    // form.maxFieldsSize = 2 * 1024 * 1024;

    // 上传文件的入口文件
    form.parse(req, (err, fields, files) => {
    
    
        if (err) {
    
    
            console.log(err);
            res.send({
    
     msg: err });
            return;
        }
        let extName = '';  //后缀名
        switch (files.file.type) {
    
    
            case 'image/pjpeg':
                extName = 'jpg';
                break;
            case 'image/jpeg':
                extName = 'jpg';
                break;
            case 'image/png':
                extName = 'png';
                break;
            case 'image/x-png':
                extName = 'png';
                break;
        }

        if (extName.length == 0) {
    
    
            res.send({
    
     msg: '图片格式不正确,只支持png和jpg格式图片' });
            return;
        }

        let index = files.file.name.indexOf('.');
        let name = files.file.name.substring(0, index);

        let avatarName = Math.random() + '---' + name + '.' + extName;
        let newPath = form.uploadDir + avatarName;
        fs.rename(files.file.path, newPath, () => {
    
    
            console.log('上传成功');
            res.send({
    
     msg: '上传成功', url: newPath });
            res.end();
        });  //重命名
    });

});

app.use(router);
app.listen('8888', function () {
    
    
    console.log('已启动,请在浏览器输入localhost:8888 访问');
});

运行 node myNode.js 即可在前台页面上传图片

猜你喜欢

转载自blog.csdn.net/document_dom/article/details/107186620