Phần 8: Upload file

Các phần trước

Phần 5: File System (P3)

Phần 6: NPM

Phần 7: Events

 

 

Module Formidable

Trong Node.js, có một module rất tốt để xử lí việc upload file đó là Formidable. Module Formiable được cài đặt bằng cách sử dựng NPM:

npm install formidable

 

Sau đó để gọi module, ta dùng phương thức require():

var formidable = require('formidable');

 

 

Upload file

Bước 1: Tạo một form Upload

Tạo một file Node.js có đinh dạng nội dung là HTML, với trường Upload:

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(8888);

 

Bước 2: Phân tích file được Upload

File sẽ được Upload và được đặt trong một thư mục tạm thời:

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(8888);

 

Bước 3: Lưu file

Sau khi file được upload lên server thành công, nó sẽ được đặt trong một thư mục tạm. Đường dẫn của thư mục có thể được tìm thấy trong đối tượng "files", nó như là tham số thứ ba được truyền trong phương thức parse() trong hàm callback. Để di chuyển file đến thư mục mà bạn chọn, sử dụng module File System, và đổi tên file: 

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.path;
      var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;
      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(8888);

 

 

Ví dụ, Upload một file demo.txt, sau đó sẽ upload file và đọc file đó trên server:

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.path;
      var newpath = '/home/tuanhiep/Desktop/' + files.filetoupload.name;
      fs.readFile(newpath, 'utf8', function(err, data){
        if(err) {
          res.writeHead(404);
          res.write('Kiểm tra lại file!');
        } else {
          res.writeHead(200);
          res.write(data);
          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(8888);

 

Kết quả trên browser: