103

何年にもわたって状況が変化しているため、より最新の情報を含む新しい回答を検討してください!

多くの新しい Node.js ライブラリは急速に時代遅れになりつつあり、とにかく例が比較的少ないため、以下を使用して画像をアップロードする方法について質問したいと思います。

  • Node.js (v0.4.1)
  • エクスプレス (1.0.7)
  • マングース (1.1.0)。

他の人はどのようにそれをしましたか?

node-formidableを見つけましたが、一般的に画像をアップロードするのは初めてなので、Node.jsとExpressを使用して一般的なこととその方法を学びたいです。

4

13 に答える 13

74

初めて自分の質問に答えます。ソースから直接例を見つけました。インデントの悪さはご容赦ください。コピーして貼り付けるときに適切にインデントする方法がわかりませんでした。コードは、GitHubの Express のmultipart/form-data例から直接取得されます。

// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');

/**
 * Module dependencies.
 */

var express = require('../../lib/express')
  , form = require('connect-form');

var app = express.createServer(
  // connect-form (http://github.com/visionmedia/connect-form)
  // middleware uses the formidable middleware to parse urlencoded
  // and multipart form data
  form({ keepExtensions: true })
);

app.get('/', function(req, res){
  res.send('<form method="post" enctype="multipart/form-data">'
    + '<p>Image: <input type="file" name="image" /></p>'
    + '<p><input type="submit" value="Upload" /></p>'
    + '</form>');
});

app.post('/', function(req, res, next){

  // connect-form adds the req.form object
  // we can (optionally) define onComplete, passing
  // the exception (if any) fields parsed, and files parsed
  req.form.complete(function(err, fields, files){
    if (err) {
      next(err);
    } else {
      console.log('\nuploaded %s to %s'
        ,  files.image.filename
        , files.image.path);
      res.redirect('back');
    }
  });

  // We can add listeners for several form
  // events such as "progress"
  req.form.on('progress', function(bytesReceived, bytesExpected){
    var percent = (bytesReceived / bytesExpected * 100) | 0;
    process.stdout.write('Uploading: %' + percent + '\r');
  });
});

app.listen(3000);
console.log('Express app started on port 3000');
于 2011-03-01T01:35:51.490 に答える
46

Express を使用しているので、bodyParser を追加するだけです。

app.use(express.bodyParser());

その後、ルートは req.files でアップロードされたファイルに自動的にアクセスできます。

app.post('/todo/create', function (req, res) {
    // TODO: move and rename the file using req.files.path & .name)
    res.send(console.dir(req.files));  // DEBUG: display available fields
});

入力コントロールに「todo」という名前を付けた場合 (Jade で):

form(action="/todo/create", method="POST", enctype="multipart/form-data")
    input(type='file', name='todo')
    button(type='submit') New

次に、「files.todo」でパスと元のファイル名を取得するまでに、アップロードされたファイルの準備ができています。

  • req.files.todo.path、および
  • req.files.todo.name

その他の便利な req.files プロパティ:

  • サイズ (バイト単位)
  • タイプ (例: 'image/png')
  • 最終更新日
  • _writeStream.encoding (例: 「バイナリ」)
于 2012-03-20T21:42:29.013 に答える
19

メイン アプリケーション ファイルの構成ブロックで、Connect Body パーサー ミドルウェアを構成できます。

    /** Form Handling */
    app.use(express.bodyParser({
        uploadDir: '/tmp/uploads',
        keepExtensions: true
    }))
    app.use(express.limit('5mb'));
于 2012-05-15T12:46:19.967 に答える
14

画像をディスクにアップロードし、その URL を MongoDB に保存するのが最善の方法です。画像を再度取得するときに休憩します。URLを指定するだけで画像が取得できます。アップロード用のコードは次のとおりです。

app.post('/upload', function(req, res) {
    // Get the temporary location of the file
    var tmp_path = req.files.thumbnail.path;
    // Set where the file should actually exists - in this case it is in the "images" directory.
    target_path = '/tmp/' + req.files.thumbnail.name;
    // Move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err)
            throw err;
        // Delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files.
        fs.unlink(tmp_path, function() {
            if (err)
                throw err;
            //
        });
    });
});

ターゲット パスを MongoDB データベースに保存します。

ここでも、画像を取得する際に、MongoDB データベースから URL を抽出し、このメソッドで使用します。

fs.readFile(target_path, "binary", function(error, file) {
    if(error) {
        res.writeHead(500, {"Content-Type": "text/plain"});
        res.write(error + "\n");
        res.end();
    }
    else {
        res.writeHead(200, {"Content-Type": "image/png"});
        res.write(file, "binary");
    }
});
于 2012-09-13T08:09:52.780 に答える
9

このコードを試してみてください。

app.get('/photos/new', function(req, res){
  res.send('<form method="post" enctype="multipart/form-data">'
    + '<p>Data: <input type="filename" name="filename" /></p>'
    + '<p>file: <input type="file" name="file" /></p>'
    + '<p><input type="submit" value="Upload" /></p>'
    + '</form>');
});


 app.post('/photos/new', function(req, res) {
  req.form.complete(function(err, fields, files) {
    if(err) {
      next(err);
    } else {
      ins = fs.createReadStream(files.photo.path);
      ous = fs.createWriteStream(__dirname + '/directory were u want to store image/' + files.photo.filename);
      util.pump(ins, ous, function(err) {
        if(err) {
          next(err);
        } else {
          res.redirect('/photos');
        }
      });
      //console.log('\nUploaded %s to %s', files.photo.filename, files.photo.path);
      //res.send('Uploaded ' + files.photo.filename + ' to ' + files.photo.path);
    }
  });
});

if (!module.parent) {
  app.listen(8000);
  console.log("Express server listening on port %d, log on to http://127.0.0.1:8000", app.address().port);
}
于 2011-11-10T05:14:30.260 に答える
8

以下を使用して、ファイルを保存するパスを設定することもできます。

req.form.uploadDir = "<path>";
于 2012-01-17T11:50:47.157 に答える
2

Express 3.0 の場合、強力なイベントを使用する場合は、マルチパート ミドルウェアを削除して、その新しいインスタンスを作成できるようにする必要があります。

これをする:

app.use(express.bodyParser());

次のように記述できます。

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart()); // Remove this line

次に、フォーム オブジェクトを作成します。

exports.upload = function(req, res) {
    var form = new formidable.IncomingForm;
    form.keepExtensions = true;
    form.uploadDir = 'tmp/';

    form.parse(req, function(err, fields, files){
        if (err) return res.end('You found error');
        // Do something with files.image etc
        console.log(files.image);
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        console.log(bytesReceived + ' ' + bytesExpected);
    });

    form.on('error', function(err) {
        res.writeHead(400, {'content-type': 'text/plain'}); // 400: Bad Request
        res.end('error:\n\n'+util.inspect(err));
    });
    res.end('Done');
    return;
};

これはブログにも投稿しまし

于 2012-12-02T08:57:42.840 に答える
0

複数のファイルをアップロードする私の方法があります:

Node.js :

router.post('/upload', function(req , res) {

var multiparty = require('multiparty');
var form = new multiparty.Form();
var fs = require('fs');

form.parse(req, function(err, fields, files) {  
    var imgArray = files.imatges;


    for (var i = 0; i < imgArray.length; i++) {
        var newPath = './public/uploads/'+fields.imgName+'/';
        var singleImg = imgArray[i];
        newPath+= singleImg.originalFilename;
        readAndWriteFile(singleImg, newPath);           
    }
    res.send("File uploaded to: " + newPath);

});

function readAndWriteFile(singleImg, newPath) {

        fs.readFile(singleImg.path , function(err,data) {
            fs.writeFile(newPath,data, function(err) {
                if (err) console.log('ERRRRRR!! :'+err);
                console.log('Fitxer: '+singleImg.originalFilename +' - '+ newPath);
            })
        })
}
})

フォームに enctype="multipart/form-data" があることを確認してください

これがあなたに手を差し伸べることを願っています;)

于 2016-10-11T19:26:35.703 に答える