Html5 ajax上传多个图片 + nodjs保存

nodejs端

var express = require("express");
var multer = require(‘multer‘);
var _ = require(‘underscore‘)
var app = express();
var done = false;

/*Configure the multer.*/
app.use(function (req, res, next) {
    res.header(‘Access-Control-Allow-Origin‘, ‘*‘);
    res.header(‘Access-Control-Allow-Methods‘, ‘GET,PUT,POST,DELETE‘);
    res.header(‘Access-Control-Allow-Headers‘, ‘Origin, X-Requested-With, Content-Type, Accept‘);
    next();
});

app.use(multer({
    dest: ‘../public/images/uploads/‘,
    rename: function (fieldname, filename) {
        return filename + Date.now();
    },
    onFileUploadStart: function (file) {
        console.log(file.originalname + ‘ is starting ...‘)
    },
    onFileUploadComplete: function (file) {
        console.log(file.fieldname + ‘ uploaded to  ‘ + file.path)
        done = true;
    }
}));

/*Handling routes.*/

app.get(‘/‘, function (req, res) {
    res.sendfile("upload.html");
});

app.post(‘/api/upload‘, function (req, res) {
    if (done == true) {
        console.log(req.files);
        res.end(_.size(req.files)+" File uploaded.");
    }
});

/*Run the server.*/
app.listen(3000, function () {
    console.log("Working on port 3000");
});

前端

<input id=‘upload‘ name="pic1" type="file" onchange="change(this)" multiple/>
<button id=‘add‘>add</button>
<button id=‘submit‘ onclick="sub()">提交啊</button>

ajax

利用xhr.send(FormData)来实现

var send2 = function(url, files) {
        var xhr = new XMLHttpRequest;
        xhr.open("POST", url, true);

        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                console.log(‘formdata‘, xhr.responseText);
            }
        };
        var fd = new FormData;

        for (var i = 0; i < files.length; i++) {
            fd.append(files[i].name, files[i])
        }
        xhr.send(fd);
    };

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。