Ajax 之【文件上传】


// 前台

var formData = new FormData(); var file = document.getElementById('myFile').files[0]; formData.append('myFile', file); var xhr = new XMLHttpRequest(); xhr.open('post', '/upload', true); xhr.upload.onprogress = function(e) { if (e.lengthComputable) { var percentage = (e.loaded / e.total) * 100; $('div.progress div.bar').css('width', percentage + '%'); } }; xhr.onerror = function(e) { showInfo('An error occurred while submitting the form. Maybe your file is too big'); }; xhr.onload = function() { showInfo(this.statusText); $('#message').val(window.location.origin + "/" + xhr.responseText.replace("\\","/")); }; xhr.send(formData);

 

//后端
var express = require('express'),
 app.use(express.bodyParser({ 
    keepExtensions: true, 
    uploadDir: __dirname + web_upload_directory,
    limit: 1024MB
  }));

app.post('/', function(req, res) {
    colog.info(Timestamp() + "File uploaded: " + req.files.myFile.path);
    var filepath = req.files.myFile.path;
    res.send(filepath.replace(web_upload_rootpath,""));
  res.end();
});

  

posted @ 2015-03-19 15:48  单先生  阅读(256)  评论(0编辑  收藏  举报