2016-07-27 12 views
1

HTMLページから画像ファイルをアップロードする必要があります。しかし、formタグを使用するつもりはないので、後でサーバーにデータを渡すために使用されるformフィールド(テキストフィールド、チェックボックスなど)があるためです。JQueryからNode JSに画像をアップロード

私のバックエンドはNode JSです。私が望むのは、Node Js最後から画像データ(ファイル)を取り出すことです。私はこの

HTML

<div class="container"> 
    <div class="row"> 
     <div class="col-xs-12"> 
     <div class="panel panel-default"> 
      <div class="panel-body"> 
      <span class="glyphicon glyphicon-cloud-upload"></span> 
      <h2>File Uploader</h2> 
      <h4>coligo.io</h4> 
      <div class="progress"> 
       <div class="progress-bar" role="progressbar"></div> 
      </div> 
      <button class="btn btn-lg upload-btn" type="button">Upload File</button> 
      </div> 
     </div> 
     </div> 
    </div> 
    </div> 
<input id="upload-input" type="file" name="uploads" multiple="multiple"></br> 

はどのように行うことができますjQueryの

$('.upload-btn').on('click', function(){ 
    $('#upload-input').click(); 
    $('.progress-bar').text('0%'); 
    $('.progress-bar').width('0%'); 
}); 

$('#upload-input').on('change', function(){ 

    var files = $(this).get(0).files; 

    if (files.length > 0){ 
    // create a FormData object which will be sent as the data payload in the 
    // AJAX request 
    var formData = new FormData(); 
     // loop through all the selected files and add them to the formData object 
    for (var i = 0; i < files.length; i++) { 
     var file = files[i]; 
var tmppath = URL.createObjectURL(event.target.files[0]); 
     // add the files to formData object for the data payload 
     formData.append('uploads', tmppath); 

    } 
    $.ajax({ 
     url: '/myp/imgup', 
     type: 'POST', 
     data: formData, 
     processData: false, 
     contentType: false, 
     success: function(data){ 
      console.log('upload successful!\n' + data); 
     }, 
     xhr: function() { 
     // create an XMLHttpRequest 
     var xhr = new XMLHttpRequest(); 

     // listen to the 'progress' event 
     xhr.upload.addEventListener('progress', function(evt) { 

      if (evt.lengthComputable) { 
      // calculate the percentage of upload completed 
      var percentComplete = evt.loaded/evt.total; 
      percentComplete = parseInt(percentComplete * 100); 

      // update the Bootstrap progress bar with the new percentage 
      $('.progress-bar').text(percentComplete + '%'); 
      $('.progress-bar').width(percentComplete + '%'); 

      // once the upload reaches 100%, set the progress bar text to done 
      if (percentComplete === 100) { 
       $('.progress-bar').html('Done'); 
      } 

      } 

     }, false); 

     return xhr; 
     } 
    }); 

    } 
}); 

NODE JS

router.post('/imgup', function(req, res){ 
    console.log(' File name '+req.files.upload); 

}); 

私は運で、数日間のためにこれを実行しようとしています。誰かが私を助けることができますか?

+0

https://github.com/felixge/node-formidable –

+0

私は以前これを疲れましたが、役に立たなかったです。私のコードで間違った方法でそれを適用することがあります。あなたはそれがどのように行われたか私に教えてくれますか? – Illep

+0

この回答はどういうわけかhttp://stackoverflow.com/a/34442688/747579? –

答えて

1

multerモジュールを使用した例は:

var express = require("express"); 
var multer = require('multer'); 
var app   = express(); 
app.get('/',function(req,res){ 
     res.sendFile(__dirname + "/index.html"); 
}); 


var storage = multer.diskStorage({ 
    destination: function (req, file, callback) { 
    callback(null, './uploads'); 
    }, 
    filename: function (req, file, callback) { 
    callback(null, file.fieldname + '-' + Date.now()); 
    } 
}); 

app.post('/api/file',function(req,res){ 
    var upload = multer({ storage : storage}).single('userFile'); 
    upload(req,res,function(err) { 
     if(err) { 
      return res.end("Error uploading file."); 
     } 
     res.end("File is uploaded"); 
    }); 
}); 

app.listen(3000,function(){ 
    console.log("Working on port 3000"); 
}); 

formidableモジュールと例:

var formidable = require('formidable'), 
http = require('http'), 
util = require('util'); 

http.createServer(function(req, res) { 
    if (req.url == '/upload' && req.method.toLowerCase() == 'post') { 
    // parse a file upload 
    var form = new formidable.IncomingForm(); 

    form.parse(req, function(err, fields, files) { 
     if (err) 
      do-smth; // process error 

     // Copy file from temporary place 
     // var fs = require('fs'); 
     // fs.rename(file.path, <targetPath>, function (err) { ... });   

     // Send result on client 
     res.writeHead(200, {'content-type': 'text/plain'}); 
     res.write('received upload:\n\n'); 
     res.end(util.inspect({fields: fields, files: files})); 
    }); 

    return; 
    } 

    // show a file upload form 
    res.writeHead(200, {'content-type': 'text/html'}); 
    res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+ 
    '<input type="text" name="title"><br>'+ 
    '<input type="file" name="upload" multiple="multiple"><br>'+ 
    '<input type="submit" value="Upload">'+ 
    '</form>' 
); 
}).listen(8080); 

Node.js - File uploadから抜粋します。元の著者はIceman,Aikon MogwaiおよびMikhailであった。アトリビューションの詳細はcontributor pageにあります。ソースはCC BY-SA 3.0でライセンスされており、Documentation archiveにあります。参照トピックID:4080.

+0

リモートファイルのアップロードにはどうすればいいですか?例:AWS S3? – Illep

+0

s3は使用されていませんが、他のクラウドプロバイダを使用しています。どちらの方法でも、ファイルがサーバーに保存された後に、アップロード機能をストレージ機能に置く必要があります。 – Iceman

関連する問題