我正在学习《The Node初学者书》并做书中的练习,练习是呈现一张用户上传的图片。这是一个用node-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) { 
      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(8888); 

我使用 node filename.js 运行它,然后打开位于 http://localhost:8888/upload 的浏览器。 ,如下所示:

我输入一个名称并选择一个文件,然后它如下:

我点击上传按钮,响应如下:

received upload: 
 
{ fields: { title: 'Hello Wolrd' }, 
  files:  
   { upload:  
      File { 
        domain: null, 
        _events: {}, 
        _eventsCount: 0, 
        _maxListeners: undefined, 
        size: 37417, 
        path: '/tmp/upload_a306115e1e630a0c548b6d820fe803cb', 
        name: 'myfile_icon_file_4.png', 
        type: 'image/png', 
        hash: null, 
        lastModifiedDate: 2016-10-11T03:52:41.052Z, 
        _writeStream: [Object] } } } 

如何获取属性路径?为什么在那里创建一个单词File

请您参考如下方法:

该属性(property)path可以通过 File 获取对象,在其代码中定义了强大的对象。正如您所写的示例所示,您的 form.parse函数给你一张 File 的 map 名为 files 的对象(去搞清楚)。因此,如果您想获得 path值到您刚刚上传的文件,您将执行以下操作(使用键 upload 因为这就是您的 html inputname ):

var pathToFile = files['upload'].path;

请记住,这仅在服务器端以您的示例编写方式可用,因此要获得这样的路径,您需要将该行代码放在 form.parse 中。功能。

您在示例中给出的打印输出来自响应,这是客户端收到的内容。 util.inspect 您用来格式化您的响应是显式转换 fieldsfiles出于调试/检查目的,将对象转换为字符串表示形式,因此这就是您无法在客户端将它们作为变量访问的原因。如果您使用我上面写的行或建议的行概念,它将访问 path只要它在你的 form.parse 内函数其中 files存在于范围内。


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!