【问题标题】:Uploading file with express-fileupload使用 express-fileupload 上传文件
【发布时间】:2018-01-31 10:26:29
【问题描述】:

我正在尝试使用 express-fileupload 上传文件,但无法让它正常工作。我可以让文件(在本例中为图像)“上传”,因为我可以让控制台显示使用正确文件夹上传的图像。

startup.js

router.get('/upload', function(req, res) {
    res.render('upload');
});

router.post('/upload', function(req, res) {
    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file 
  let startup_image = req.files.image;

  // Use the mv() method to place the file somewhere on your server 
  startup_image.mv('/images' , function(err) {
      if (err) {
          console.log(err);
      }
  });
});

那么我的html表单就是

<form ref='uploadForm' 
      id='uploadForm' 
      action='/upload' 
      method='post' 
      encType="multipart/form-data">
        <input type="file" name="image" />
        <input type='submit' value='Upload!' />
</form>

【问题讨论】:

  • 它会返回一个err 供我们查看吗?
  • 只给出了这个,但我没有运气弄清楚它的含义Error: ENOENT: no such file or directory, open '/images/josh.jpg'
  • 请检查更新
  • 如果有效请告诉我

标签: node.js express file-upload


【解决方案1】:

您正在指向文件所在的目录,但您没有给它一个文件名。我想说让用户决定客户端的文件名并将其添加到路径中。

<input name="userFileName" type="text">//userFilename Here</input>
var myFILENAME = req.body.userFilename 
startup_image.mv('/images/'+myFILENAME+'.jpg', ..) //myFILENAME needs to be added here

另请参阅 how to upload files with express-fileupload 中的完整示例

更新

我找到了您的问题的解决方案,您需要将 __dirname 添加到此行,这将使程序知道您的当前目录到您的 source 代码。

startup_image.mv(__dirname + '/images' , function(err) {..

更新 2

这是我的源代码,如果你愿意,可以试试这个。

我的html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form ref='uploadForm' encType="multipart/form-data" class="" action="/upload" method="post">
      <input type="text" name="fileName" value=""><br>
      <input type="file" name="foo" value=""><br>
      <input type="submit" name="" value="upload!">
    </form>
  </body>
</html>

我的主要来源

var express = require("express);
var app = express();
const fileUpload = require('express-fileupload');
//npm install ejs, express, express-fileupload

//middleware
app.use(express.static(__dirname));
app.set('view engine', 'ejs');
app.use(fileUpload());

app.get('/inputFile', function(req, res){
  res.render('inputt');
});

app.post('/upload', function(req, res) {
  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
   var startup_image = req.files.foo;
   var fileName = req.body.fileName;
   // Use the mv() method to place the file somewhere on your server
   startup_image.mv(__dirname + '/images/' + fileName + '.jpg' , function(err) {
     if(err){
       console.log(err);
     }else{
    console.log("uploaded");
}
   });
 });

app.listen(7777);

【讨论】:

  • 谢谢,我找到了让我到达当前位置的链接。我更新了我的代码,使其文件名来自您发布的变量。仍然出现同样的错误Error: ENOENT: no such file or directory, open '/images/josh.jpg'
  • @SeaitManageit 请检查更新,需要放完整路径
  • 所以我的代码现在是router.post('/upload', function(req, res) { // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file let startup_image = req.files.image; var fileName = req.body.fileName; // Use the mv() method to place the file somewhere on your server startup_image.mv(__dirname + '/images/' + fileName + '.jpg' , function(err) { if(err){ console.log(err); } }); }); 它显示了正确的路径(排序,希望它上一个目录来保存图像)但实际图像从未出现在我的文件夹中页面被卡住加载
  • 我在构建测试应用程序时使用 c9.io 托管测试应用程序,我收到错误 502 - Bad Gatewayafter 页面加载约 2 分钟后,它会从 c9.io 打印出一个 html 文件
  • 我已经放了我的资源代码,它对我来说很好,请检查一下@SeaitManageit
【解决方案2】:

使用异步/等待风格

在您的服务器文件中执行此操作

const fileUpload = require('express-fileupload');

 app.use(
  fileUpload({
    limits: { fileSize: 50 * 1024 * 1024 },
    useTempFiles: true,
   // dir for windows PC
    tempFileDir: path.join(__dirname, './tmp'),
  }),
);

然后在您的控制器中,执行此操作

  const file = req.files.filename;
  await file.mv(file.name);

  if (!file || Object.keys(req.files).length === 0) {
    return res.status(400).console.error('No files were uploaded.');
  }

【讨论】:

  • 你是一个救生员。 #尊重
  • 很高兴它有帮助!
【解决方案3】:

此解决方案适用于非 ejs 和导出模块解决方案:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>File Upload</title>
  </head>
  <body>
    <form ref='uploadForm' encType="multipart/form-data" class="" action="/path/to/nodejs/upload/file" method="post">
      <input type="file" name="my_file"><br>
      <input type="submit" name="" value="upload">
    </form>
  </body>
</html>

现在是 NodeJS

const express = require("express");
const app = express();
const fileUpload = require('express-fileupload');

app.use(fileUpload({ safeFileNames: true, preserveExtension: true }))

app.post('/', function(req, res) {
    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
    let the_file = req.files.my_file;

    the_file.mv('/path/to/html/uploads/up/' + the_file.name , function(err) {

        res.writeHead(200, {"Content-Type": "text/plain"});
        if(err){
            console.log(err);
            res.write(err);
            res.end();
        } else {
            console.log("uploaded");
            res.write("upload of file "+the_file.name+" complete");
            res.end();
        } 

   });

});

module.exports = app;

【讨论】:

    【解决方案4】:

    你必须创建文件夹images

    【讨论】:

      【解决方案5】:
      //install path module 
      const path = require('path');
      
       // remaining code
      
      let startup_image = req.files.image;
      
      startup_image.mv(path.resolve(__dirname,'/images',startup_image.name), function(error){
        //remaining code
      })
      

      【讨论】:

      • 欢迎来到 StackOverflow。给出解决方案时请使用完整的句子/代码示例。很难理解你的答案。您不仅会帮助您正在回答的人,而且会帮助将来有类似问题的许多其他开发人员。
      【解决方案6】:

      这样 file.mv(path.resolve(__dirname, '../public/images', 文件名)

      【讨论】:

        猜你喜欢
        • 2019-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-16
        • 2015-07-09
        • 2021-03-22
        • 2019-06-19
        • 1970-01-01
        相关资源
        最近更新 更多