web-dev-qa-db-fra.com

comment télécharger un fichier image et l'afficher avec express nodejs

J'ai utilisé le code suivant:

fileupload.html

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="http://127.0.0.1:8081/file_upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

fileupload.js:

var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var multer  = require('multer');

//console.log(multer);

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));

app.get('/fileupload.html', function (req, res) {
   res.sendFile( __dirname + "/" + "fileupload.html" );
})

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

   console.log(req.files.file.name);
   console.log(req.files.file.path);
   console.log(req.files.file.type);

   var file = __dirname + "/" + req.files.file.name;
   fs.readFile( req.files.file.path, function (err, data) {
        fs.writeFile(file, data, function (err) {
         if( err ){
              console.log( err );
         }else{
               response = {
                   message:'File uploaded successfully',
                   filename:req.files.file.name
              };
          }
          console.log( response );
          res.end( JSON.stringify( response ) );
       });
   });
})

var server = app.listen(8081, function () {
  var Host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", Host, port)
})

J'ai utilisé ces codes ci-dessus pour le téléchargement de fichiers, mais lors de l'exécution à l'aide du noeud fileupload.js dans le terminal, j'obtiens une erreur de type TypeError('app.use() requires middleware functions'); 

Quelqu'un peut-il aider à résoudre ce problème.

9
Khushboo

Vous essayez d'utiliser l'ancienne API de multer. Cela a changé un peu en arrière, voir documentation pour plus d'informations.

Dans votre cas particulier de téléchargement d'un seul fichier, vous devez supprimer la ligne app.use(multer({ ... })) et utiliser plutôt .single() et req.file comme

var upload = multer({ dest: '/tmp/'});

// File input field name is simply 'file'
app.post('/file_upload', upload.single('file'), function(req, res) {
  var file = __dirname + '/' + req.file.filename;
  fs.rename(req.file.path, file, function(err) {
    if (err) {
      console.log(err);
      res.send(500);
    } else {
      res.json({
        message: 'File uploaded successfully',
        filename: req.file.filename
      });
    }
  });
});
13
mscdex

Multer ajoute un objet body et un fichier ou un objet files à l'objet request. L'objet body contient les valeurs des champs de texte du formulaire, l'objet file ou files contient les fichiers chargés via le formulaire.

Utilisez ce code, espérons que cela vous aidera.

var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var multer = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
var upload = multer({ dest: '/tmp' })

app.get('/fileupload.html', function (req, res) {
   res.sendFile( __dirname + "/" + "fileupload.html" );
})

app.post('/file_upload', upload.single("file"), function (req, res) {
   var file = __dirname + "/" + req.file.originalname;
   fs.readFile( req.file.path, function (err, data) {
        fs.writeFile(file, data, function (err) {
         if( err ){
              console.error( err );
              response = {
                   message: 'Sorry, file couldn\'t be uploaded.',
                   filename: req.file.originalname
              };
         }else{
               response = {
                   message: 'File uploaded successfully',
                   filename: req.file.originalname
              };
          }
          res.end( JSON.stringify( response ) );
       });
   });
})

var server = app.listen(8081, function () {
  var Host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", Host, port)
})
3
Vikash Kumar

La solution ci-dessus ne fonctionne pas pour moi alors j'ai utilisé la méthode de stockage:

var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var multer  = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/index.htm', function (req, res) {
    res.sendFile( __dirname + "/" + "index.htm" );
})


var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        var ext = require('path').extname(file.originalname);
        ext = ext.length>1 ? ext : "." + require('mime').extension(file.mimetype);
        require('crypto').pseudoRandomBytes(16, function (err, raw) {
            cb(null, (err ? undefined : raw.toString('hex') ) + ext);
        });
    }
});

var upload = multer({ storage: storage });

app.post('/file_upload', upload.any(), function (req, res, next) {
    res.send(req.files);
})
1
Pardeep Kumar

cela fonctionne pour moi correctement

var express = require('express'),
    http = require('http'),
    formidable = require('formidable'),
    fs = require('fs'),
    path = require('path');
var bodyParser = require('body-parser');
var multer  = require('multer');
var upload = multer({ dest: '/tmp/'});
var app = express();


app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname + '/index.html'));
});

var server = app.listen(3000, function() {
  console.log('leistening on port', server.address().port);
})

app.post('/upload', upload.single('file'), function(req, res) {
  var file = 'uploads' + '/' + req.file.originalname;
  fs.rename(req.file.path, file, function(err) {
    if (err) {
      res.send(500);
    } else {
      res.json({
        message: 'File uploaded successfully',
        filename: req.originalname
      });
    }
  });
});
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
            <form action="http://127.0.0.1:3000/upload" enctype="multipart/form-data" method="post">
                <input type="text" name="title">
                <input type="file" name="file">
                <input type="submit" value="Upload">
                
            </form>
    </body>
</html>

0
shuts13