Node.js + jQuery Ajax。 サーバーへのファイルのアップロード

はじめに



この記事では、jQuery Ajaxを使用してNode.jsサーバーにファイルをアップロードする方法について説明します。 はい、他のソリューション、たとえばJQuery File Uploadが既にあることは理解していますが、それでもすべてがどのように機能するかを理解するために、既存の何かをしたいことがあります。 このソリューションはケーススタディであり、コードに関するすべてのコメントや、コードを改善するための提案をコメントに残してください。



使用するもの



  1. ブートストラップ
  2. JQuery
  3. Node.js Multipartyのモジュール




Ajaxを使用してファイルを送信する



ページ上のすべての要素は手動で作成されます。 JSUploaderクラスは読み込みを担当します。uploadFileメソッドの1つを次に示します。



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







次は、投稿を処理し、ホームページのリクエストを取得するコードです。 ここで、アップロードフォームを表示し、投稿リクエストを処理してファイルをダウンロードします。

ダウンロードの最後に、すべてが正常であること、またはエラーがある場合は送信します。 私の意見では唯一の問題は、このコードでは、サーバーがダウンロードをすぐに完了してエラーを報告できないため、ファイルが完全にダウンロードされるまで待つ必要があるということです。 フォームのoncloseシグナルを何らかの方法で呼び出すと、問題の解決は可能ですが、残念ながら、まだ解決策が見つかりませんでした。



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







参照資料






All Articles