Code ví dụ Node.js Upload File với module Formidable

Code ví dụ Node.js Upload File với module Formidable.

Module Formidable

Module formidable là một module rất tuyệt vời để làm việc với form, file uploads.

(Xem lại: Ví dụ submit form bằng module Formidable)

Để cài đặt module formidable ta dùng lệnh:

npm install formidable

Để include module formidable vào project ta dùng method:

var formidable = require('formidable');

Upload file với module formidable

Ở đây mình sử dụng module http để tạo server, module fs để lưu file upload tới nơi chỉ định

URL /fileupload được sử dụng để xử lý file upload.

Các URL còn lại sẽ hiển thị trang upload 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;
    console.log('oldpath' + oldpath);
      var newpath = 'C:/Users/superman/file-upload/' + files.filetoupload.name;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        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);

var form = new formidable.IncomingForm(); : đối tượng form chứa các thông tin submit từ form (gồm file và các parameter)

var oldpath = files.filetoupload.path; : là đường dẫn của file sau khi được upload lên server (mặc định nó sẽ lưu vào thư mục đệm/temp)

fs.rename(oldpath, newpath, function (err) : di chuyển file được upload từ thư mục temp sang vị trí muốn lưu. (Trong ví dụ này mình lưu vào folder C:/Users/superman/file-upload)

Demo

Chạy file server.js

Truy cập url localhost:8080 sẽ thấy giao diện upload file

Code ví dụ Node.js Upload File với module Formidable

Ở đây mình thực hiện upload file demo.txt

Code ví dụ Node.js Upload File với module Formidable

Kết quả:

Code ví dụ Node.js Upload File với module Formidable

Code ví dụ Node.js Upload File với module Formidable

Xem ở phần log, bạn sẽ thấy đường dẫn ban đầu lúc file được upload lên thư mục temp của hệ điều hành.

Code ví dụ Node.js Upload File với module Formidable

 

Okay, Done!

Download code ví dụ trên tại đây.

 

References:

https://www.npmjs.com/package/formidable

stackjava.com