2016-10-11 50 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