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

  

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