Node.js อัปโหลดไฟล์
โมดูลที่น่าเกรงขาม
มีโมดูลที่ดีมากสำหรับการทำงานกับการอัพโหลดไฟล์ที่เรียกว่า "Formidable"
โมดูล Formidable สามารถดาวน์โหลดและติดตั้งได้โดยใช้ NPM:
C:\Users\Your Name>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: แยกวิเคราะห์ไฟล์ที่อัปโหลด
รวมโมดูลที่น่าเกรงขามเพื่อให้สามารถแยกวิเคราะห์ไฟล์ที่อัปโหลดเมื่อถึงเซิร์ฟเวอร์
เมื่อไฟล์ถูกอัปโหลดและแยกวิเคราะห์ ไฟล์จะถูกวางไว้ในโฟลเดอร์ชั่วคราวในคอมพิวเตอร์ของคุณ
ตัวอย่าง
ไฟล์จะถูกอัปโหลดและวางไว้ในโฟลเดอร์ชั่วคราว:
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('File
uploaded');
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()
ฟังก์ชันเรียกกลับของเมธอด
ในการย้ายไฟล์ไปยังโฟลเดอร์ที่คุณเลือก ให้ใช้โมดูล 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/Your Name/' + files.filetoupload.originalFilename;
fs.rename(oldpath, newpath, function (err) {
if (err) throw
err;
res.write('File uploaded
and moved!');
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);