2016-10-11 58 views
0

我正在学习“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,当属以下东西:

enter image description here

我进入名称并选择一个文件,然后说到如下:

enter image description here

我点击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] } } } 

如何获得财产path?为什么在这里创建一个单词File

+0

这是'强大'库的内部表示。 “文件”的一个实例。你可以通过以下途径访问路径:'files.upload.path' – notion

+0

我试过了,但是出现错误:'TypeError:无法读取未定义的属性'路径',如何? – Rico

回答

0

属性path可用于File对象,该对象在其代码中定义。以你的例子为例,你的form.parse函数给你一个File对象的地图,叫做files(去图)。因此,如果你想获得path价值给你刚刚上传,你会做下列文件(使用键upload因为这是inputname是你的HTML):

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

记住,这只会在您的示例写入的方式中可用于服务器端,因此为了获得这样的路径,您可以将该行代码放入form.parse函数中。

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