📜 ⬆️ ⬇️

Node.js + jQuery Ajax. Upload files to server

Introduction


In this article, I want to tell you about my way of uploading files to the Node.js server using jQuery Ajax. Yes, I understand that there are already other solutions, for example, jQuery File Upload , but still sometimes you want to make something that already exists, in order to understand how it all works. This solution is a case study, all comments about the code or suggestions for improving it leave in the comments.

What will we use


  1. Bootstrap
  2. Jquery
  3. Module for Node.js Multiparty


Sending a file using Ajax


All elements on the page are created manually. The JSUploader class is responsible for uploading one of its uploadFile methods:

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

')

File upload processing


To upload files to the server, we need a multiparty module, which can be installed using the command in the console:
npm install multiparty

Further the code which processes post and get requests of initial page. Here we display the upload form and process the post request to download the file.
When the download is finished, we inform the client that everything is fine or if there are errors, then send them. The only problem in my opinion is that in this code the server cannot immediately complete the download and report an error, for this you have to wait for the file to load completely. The solution to the problem is possible if we somehow call the signal on close on the form, but unfortunately so far I have not found a solution.

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


Links


Source: https://habr.com/ru/post/229743/


All Articles