Node.js 上傳檔案
Formidable 模組
有一個非常好的模組用於處理檔案上傳,稱為“Formidable”。
可以使用 NPM 下載和安裝 Formidable 模組
C:\Users\你的名字>npm install formidable
下載 Formidable 模組後,您可以將其包含在任何應用程式中
var formidable = require('formidable');
上傳檔案
現在您可以建立 Node.js 網頁,讓使用者將檔案上傳到您的計算機
步驟 1:建立上傳表單
建立一個 Node.js 檔案,寫入一個包含上傳欄位的 HTML 表單
示例
此程式碼將生成一個 HTML 表單
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}).listen(8080);
步驟 2:解析上傳的檔案
包含 Formidable 模組,以便在檔案到達伺服器後解析上傳的檔案。
當檔案上傳並解析後,它會被放置在您計算機上的一個臨時資料夾中。
示例
檔案將被上傳,並放置在臨時資料夾中
var http = require('http');
var formidable = require('formidable');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.write('檔案已上傳');
res.end();
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
步驟 3:儲存檔案
當檔案成功上傳到伺服器時,它會被放置在一個臨時資料夾中。
此目錄的路徑可以在 parse()
方法的回撥函式中作為第三個引數傳遞的 "files" 物件中找到。
要將檔案移動到您選擇的資料夾,請使用 File System 模組並重命名檔案
示例
包含 fs 模組,並將檔案移動到當前資料夾
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.filepath;
var newpath = 'C:/Users/你的名字/' + files.filetoupload.originalFilename;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('檔案已上傳並移動!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);