ajax文件上传(单张上传、多张上传)

server.js

var express = require("express");
var app = express();
app.use(express.static("www"));

var bodyparser = require("body-parser");
app.use(bodyparser.urlencoded({
    extended: false
}));

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/image");
var imgSchema = new mongoose.Schema({
    name: String,
    content: String,
    img: Array
});
var Img = mongoose.model("Img", imgSchema);

var multer = require("multer");
var upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, "./www/images");
        },
        filename: function (req, file, cb) {
            var filename = Date.now() + file.originalname;
            // console.log(filename);
            req.img.push(filename);
            cb(null, filename);
        }
    })
});

// 上传单张图片
app.post("/upload/single", upload.single("photo"), (req, res) => {
    res.json({
        err: 0,
        msg: "上传图片完毕"
    });
});

// 上传多张图片
app.post("/upload/multiple", (req, res, next) => {
    req.img = [];
    next();
}, upload.array("photo"), (req, res) => {
    // console.log(req.body);
    // console.log(req.img);
    var img = new Img({
        ...req.body,
        img: req.img
    });
    img.save();
    res.json({
        err: 0,
        msg: "上传图片完毕"
    });
});

app.listen(3000, () => {
    console.log("服务器启动成功");
});

单张照片上传页面

<!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">
    <title>单张图片上传</title>
    <style>
        label#add {
            display: block;
            width: 100px;
            height: 100px;
            border: 2px solid black;
            text-align: center;
            line-height: 100px;
            font-size: 100px;
            background-size: 100% 100%;
        }
    </style>
</head>

<body>
    <form id="single-form">
        <label for="photo" id="add" title="点击选择文件或者将文件拖拽到此处">+</label>
        <input type="file" id="photo" accept="image/*" style="display:none;">
        <button>上传</button>
    </form>
</body>

</html>
<script src="/jquery.js"></script>
<script>
    // 定义一个全局变量file,保存当前选取的图片对象
    var file = null;

    // 1.点击+,选取图片
    $("#photo").on("change", function (e) {
        // console.log(e.target.files);
        // 拿到当前选择的文件对象
        file = e.target.files[0];
        // console.log(file);
        // 生成路径
        var url = URL.createObjectURL(file);
        $("#add").css("background-image", "url(" + url + ")").text("");
    });

    // 2.拖拽图片(文件)drag(拽) + drop(丢)
    // ondragover 在标签元素上拖拽时触发
    document.ondragover = function (e) {
        // console.log("ondragover");
        // 阻止默认事件
        e.preventDefault();
        // 阻止消息的传播
        e.stopImmediatePropagation();
    }
    // ondrop 当拖拽的鼠标在窗口中松开时触发
    document.ondrop = function (e) {
        // console.log(e);
        // console.log("ondrop");
        // 阻止默认事件
        e.preventDefault();
        // 阻止消息的传播
        e.stopImmediatePropagation();
    }
    $("#add").on("drop", function (e) {
        // 类似原生的事件对象e
        // console.log(e.originalEvent);
        file = e.originalEvent.dataTransfer.files[0];
        // 生成路径
        var url = URL.createObjectURL(file);
        $("#add").css("background-image", "url(" + url + ")").text("");
    });

    // 3.点击按钮上传图片
    $("#single-form").on("submit", function (e) {
        e.preventDefault();
        // 如果表单中有文件,那么不能使用 $(this).serialize() 获取数据
        if (!file) {
            alert("请选择一个图片");
            return;
        }
        // 准备本次请求需要发送的表单数据
        var postData = new FormData();
        // 把要上传的数据拼接到表单数据中
        postData.append("photo", file);
        // 发送请求:文件上传需要使用post请求,但不能直接使用$.post(),因为文件上传请求的数据格式需要multipart/form-data
        // 格式的数据,所以需要发起自定义的ajax请求
        $.ajax({
            method: "POST",
            url: "/upload/single",
            data: postData,
            // 本次上传的请求数据类型,false:表示不使用x-www-form-urlencoded,让jquery根据data内容类型自动生成
            contentType: false,
            // 请求数据是否需要经过jquery加工处理
            processData: false,
        }).then(function (data) {
            console.log(data);
        });
    });
</script>

多张照片上传

<!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">
    <title>多张图片上传</title>
    <style>
        * {
            box-sizing: border-box;
        }

        #img-list {
            display: flex;
            flex-wrap: wrap;
            width: 300px;
        }

        .img-list-item {
            border: 1px solid black;
            width: 100px;
            height: 100px;
            background-size: 100% 100%;
            position: relative;
        }

        #file-label {
            border: 2px solid black;
            display: block;
            text-align: center;
            line-height: 100px;
            font-size: 100px;
            font-weight: bold;
        }

        .remove {
            width: 20px;
            height: 20px;
            background-color: red;
            border-radius: 50%;
            text-align: center;
            line-height: 20px;
            position: absolute;
            right: 0px;
        }
    </style>
</head>

<body>
    <div id="img-list">
        <label for="file" id="file-label" class="img-list-item">+</label>
        <input type="file" id="file" accept="image/*" multiple style="display:none;">
    </div>
    <input id="name" type="text" name="name">
    <textarea id="content" cols="30" rows="10" name="content"></textarea>
    <button id="btn-commit">上传</button>
</body>

</html>
<script src="/jquery.js"></script>
<script>
    // 定义全局变量,保存目前已经选择过的图片文件对象
    var files = [];
    // 监听input的change事件
    $("#file").on("change", function (e) {
        // console.log(e.target.files);
        // 拿到本次选取的文件
        var fs = e.target.files;
        for (var i = 0; i < fs.length; i++) {
            // 判断总容器文件的个数
            if (files.length < 9) {
                files.push(fs[i]);
                // console.log(files.length);
            } else {
                alert("最多只能上传9张图片");
                break;
            }
        }
        renderImage();
    });

    // 渲染图片
    function renderImage() {
        // 重新渲染之前,把旧的图片div先删掉
        $(".can-remove").remove();
        // 重新渲染
        files.forEach(function (f, i) {
            // 生成路径url
            var url = URL.createObjectURL(f);
            // 生成对应的div显示图片
            var div = $("<div class='can-remove'><div class='remove' index=" + i + ">×</div></div>")
                .addClass("img-list-item").css("background-image", "url(" + url + ")");
            // 拼接到 + 号前面
            $("#file-label").before(div);
        });
        // 如果图片已经够9张,不显示 + 
        if (files.length >= 9) {
            $("#file-label").hide();
        } else {
            $("#file-label").show();
        }
    }

    // 删除按钮(代理事件)
    $("#img-list").on("click", ".remove", function () {
        // alert("点击了删除按钮" + $(this).attr("index"));
        files.splice($(this).attr("index"), 1);
        renderImage();
    });

    $("#btn-commit").on("click", function () {
        if (files.length <= 0) {
            alert("请选择一个图片");
            return;
        }

        // 准备本次请求需要发送的表单数据
        var postData = new FormData();
        files.forEach(function (f) {
            postData.append("photo", f);
            console.log(postData);
        });

        postData.append("name", $("#name").val());
        postData.append("content", $("#content").val());

        $.ajax({
            method: "POST",
            url: "/upload/multiple",
            data: postData,
            contentType: false,
            processData: false,
        }).then(function (data) {
            console.log(data);
        });
    });
</script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值