码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-04-03 07:00:38      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

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);
    };

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

标签:

原文地址:http://my.oschina.net/u/588574/blog/395489

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!