【问题标题】:How to find out file size in Node?如何在Node中找出文件大小?
【发布时间】:2017-01-14 07:09:39
【问题描述】:

我有一个应用程序来推断用户上传的文件的大小。我的代码如下

server.js代码如下

var express = require('express');
var formidable = require('express-formidable');
var fs = require('fs');

var app = express();

var PORT = 8080;

app.use(express.static(__dirname+'/views'));

app.use(formidable.parse());

app.set('views', './views');

app.set('view engine', 'jade');

app.get('/', function(req, res){
   res.render('index.jade'); 
});

当我尝试记录下面的变量统计信息时,我收到一条错误消息

TypeError:路径必须是字符串

app.post('/upload', function(req, res){
   var stats = fs.statSync(req.body);
   console.log(stats);
});

app.listen(PORT, function(){
    console.log('Express listening on port: '+PORT);
});

index.jade 文件如下渲染

html
    head
        link(rel='stylesheet', href='style.css', type='text/css')
        title Upload file for shortening
    body
        h1 Welcome to file metadata service
        div(id='upload-button')
            form(action='/upload', enctype='multipart/form-data')
                input(name='Upload', type='file', id='upload-butt')
        div(id="submit-button")
            form(action = '/submit')
                button(type="submit", value='Submit', id='submit-butt') Submit

        script(src="https://code.jquery.com/jquery-2.2.0.min.js")
        script(src="upload.js")

css 样式如下

#submit-butt{
    width:100px;
    height:auto;
    background-color:red;
    cursor:pointer;
    margin-left:150px;
}

#upload-butt{
    width:200px;
    height:auto;
    cursor:pointer;
    float:left;
}

h1{
    font-family:Impact;
}

jQuery代码如下

$('#upload-butt').on('click', function(){
   $('#upload-butt').on('change', function(){
      var file = $(this).get(0).files;

      if(file.length > 0){
          var formData = new FormData();
          formData.append('Upload', file, file.name);
          $.ajax({
              url: '/upload', 
              type: 'POST',
              data:formData,
              processData:false,
              contentType:false,
              success: function(data){
                  console.log('upload successful: '+data);
              }
          })
      }
   });
});

如何处理 TypeError?如何将路径转换为字符串?我所拥有的是经过强大的中间件运行后得到的解析数据。

【问题讨论】:

  • 上传端点的 req.body 值是多少?
  • req.body 可能是一个对象,fs 正在寻找一个路径字符串
  • @bmartin - 当我尝试记录 req.body 时,我得到的只是对象 {Upload: ' '}
  • @VinnieJames - 是的,我知道。我的问题是如何将其转换为文件路径?
  • 只能在前端查看文件的大小。您甚至可以在上传文件之前执行此操作。只需使用“*.size”参数。例如var size = file.size;

标签: javascript jquery node.js


【解决方案1】:

将后端的“/upload”更改为此代码。不要在其中使用 req 参数。没必要。

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

  // create an incoming form object
  var form = new formidable.IncomingForm();

  // specify that we want to allow the user to upload multiple files in a single request
  form.multiples = true;

  // store all uploads in the /uploads directory
  form.uploadDir = path.join(__dirname, '/uploads');

  // every time a file has been uploaded successfully,
  // rename it to it's orignal name
  form.on('file', function(field, file) {
    fs.rename(file.path, path.join(form.uploadDir, file.name));
  });

  // log any errors that occur
  form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
  });

  // once all the files have been uploaded, send a response to the client
  form.on('end', function() {
    res.end('success');
  });

  // parse the incoming request containing the form data
  form.parse(req);

});

【讨论】:

  • 我在尝试此操作时收到此错误。 TypeError: formidable.IncomingForm 不是函数
  • var formidable = require('formidable');var form = new formidable.IncomingForm();检查这两件事
  • 嘿,谢谢!我必须使用强大的模块,而不是快速强大的模块。感谢那!关于如何使用它来获取文件大小的任何想法?我在任何地方都看不到路径字段,所以我假设我不能在这里使用 fs 模块
  • 您可以从前端本身获取文件大小。即使您想在 nodejs 中执行此操作,也可以使用 fs.statSync(filename)。您已经有了路径,它在 /uploads 文件夹中,并且文件名也在 file.name 中指定:) 试一试。
  • 是的,我试过了 form.on('file', function(field, file) { fs.rename(file.path, path.join(form.uploadDir, file.name)); console.log('在这里'); console.log(fs.statSync(file.name)); });这似乎不起作用。未输入回调函数,因为没有记录任何内容。
猜你喜欢
  • 2021-01-23
  • 2011-04-26
  • 1970-01-01
  • 2017-07-10
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
相关资源
最近更新 更多