this.uploadFile = function(index) { //baseClass this var file = baseClass.allFiles[index]; // FormData var data = new FormData(); // data.append('uploadFile', file.file); // Ajax $.ajax({ url: '/', data: data, cache: false, contentType: false, processData: false, type: 'POST', success: function(response) { var message = file.element.find('td.message'); if(response.status == 'ok') { message.html(response.text); file.element.find('button.uploadButton').remove(); } else { message.html(response.errors); } }, xhr: function() { var xhr = $.ajaxSettings.xhr(); if ( xhr.upload ) { console.log('xhr upload'); xhr.upload.onprogress = function(e) { file.progressDone = e.position || e.loaded; file.progressTotal = e.totalSize || e.total; // baseClass.updateFileProgress(index, file.progressDone, file.progressTotal, file.element); // baseClass.totalProgressUpdated(); }; } return xhr; } }); };
npm install multiparty
var express = require('express'), router = express.Router(), fs = require("fs"), multiparty = require('multiparty'); // router.get('/', function(req, res) { res.render('index', { title: 'Node.js File Uploads' }); }); // router.post('/', function(req, res, next) { // var form = new multiparty.Form(); // , var uploadFile = {uploadPath: '', type: '', size: 0}; // var maxSize = 2 * 1024 * 1024; //2MB // ( jpeg,jpg png) var supportMimeTypes = ['image/jpg', 'image/jpeg', 'image/png']; // var errors = []; // form.on('error', function(err){ if(fs.existsSync(uploadFile.path)) { // fs.unlinkSync(uploadFile.path); console.log('error'); } }); form.on('close', function() { // if(errors.length == 0) { // res.send({status: 'ok', text: 'Success'}); } else { if(fs.existsSync(uploadFile.path)) { // fs.unlinkSync(uploadFile.path); } // res.send({status: 'bad', errors: errors}); } }); // form.on('part', function(part) { // uploadFile.size = part.byteCount; // uploadFile.type = part.headers['content-type']; // uploadFile.path = './files/' + part.filename; // , if(uploadFile.size > maxSize) { errors.push('File size is ' + uploadFile.size + '. Limit is' + (maxSize / 1024 / 1024) + 'MB.'); } // if(supportMimeTypes.indexOf(uploadFile.type) == -1) { errors.push('Unsupported mimetype ' + uploadFile.type); } // if(errors.length == 0) { var out = fs.createWriteStream(uploadFile.path); part.pipe(out); } else { // // - onclose part.resume(); } }); // form.parse(req); });
Source: https://habr.com/ru/post/229743/
All Articles