Gửi tệp trong nodejs

Trọng Express. js, việc tải File lên hơi khó vì tính chất không đồng bộ và cách tiếp cận mạng của nó

Nó có thể được thực hiện bằng cách sử dụng phần mềm trung gian để xử lý dữ liệu đa phần / biểu mẫu. Có nhiều phần mềm trung gian có thể được sử dụng như multer, connect, body-parser, v. v

Vui lòng lấy một ví dụ để chứng minh tải lên tệp trong Node. js. Ở đây, chúng tôi đang sử dụng phần mềm trung gian 'multiter'

Các bài viết liên quan

  • Ví dụ về Tải lên tệp Laravel VueJS bằng Vue-dropzone
  • Truyền tệp tải xuống trong Laravel
  • Hệ thống tệp trong nút. js
  • Hướng Dẫn Nhanh. js
  • Cấu hình Laravel application application

Tạo một thư mục “tải lên tệp jtp” có các tệp sau

Gửi tệp trong nodejs

tải lên. Nó là một thư mục trống, tức là được tạo ra để lưu trữ các hình ảnh đã tải lên

bưu kiện. This is JSON file, has data after

Gửi tệp trong nodejs

Tập tin. mục lục. html

Gửi tệp trong nodejs

Tập tin. người phục vụ. js

Gửi tệp trong nodejs

To install package. json, hãy thực hiện đoạn mã sau

npm install

Nó sẽ tạo một thư mục mới “node_modules” bên trong thư mục “jtp file upload”

cài đặt npm

Gửi tệp trong nodejs
  • Các phần phụ thuộc đã được cài đặt. Bây giờ, hãy chạy máy chủ
  • Chọn một hình ảnh để tải lên và nhấp vào nút "Tải lên"

Tại đây, bạn thấy rằng tệp đã được tải lên thành công. Bạn có thể xem tệp đã tải lên trong thư mục "tải lên"

Ở đây mình dùng module

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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
2 để tạo server, module
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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
3 để lưu file upload tới nơi chỉ định

URL 

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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
4 được sử dụng để xử lý tệp tải lên

URL còn lại sẽ hiển thị tệp tải lên của trang

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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);

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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
5. biểu mẫu đối tượng chứa các thông tin gửi từ biểu mẫu (bao gồm tệp và tham số)

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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
6. là đường dẫn của tệp sau khi được tải lên máy chủ (mặc định nó sẽ lưu vào thư mục đệm/tạm thời)

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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
7. tập tin chuyển đổi được tải lên từ thư mục tạm thời sang vị trí muốn lưu. (Trong ví dụ này mình lưu vào thư mục 
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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
8)

Thử nghiệm

Chạy tệp

var formidable = require('formidable');
0

Gửi tệp trong nodejs

Truy cập url

var formidable = require('formidable');
1 sẽ thấy giao diện tải lên tệp

Gửi tệp trong nodejs

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

var formidable = require('formidable');
2

Gửi tệp trong nodejs

Kết quả

Gửi tệp trong nodejs

Gửi tệp trong nodejs

Xem ở phần nhật ký, bạn sẽ thấy đường dẫn ban đầu khi tệp được tải lên thư mục tạm thời của hệ điều hành

Trong bài viết này chúng ta sẽ cùng nhau xây dựng một trang web upload file sử dụng NodeJS, bài viết này mình sẽ cố gắng đi từng bước và giải thích kỹ thuật code từng đoạn sao cho dễ hiểu nhất. Mình sẽ sử dụng kết hợp giữa các module như module khủng để parse form, module http giúp khởi tạo HTTP Web Server, module fs để xử lý file

Gửi tệp trong nodejs

Bài viết này đã được đăng tại freetuts. net , không được sao chép dưới mọi hình thức.

1. Mô-đun ghê gớm

Có rất nhiều module hữu ích cho việc upload file sử dụng Nodejs, mình sẽ sử dụng module ghê gớm. Để cài đặt mô-đun này, bạn cần mở thiết bị đầu cuối và nhập dòng lệnh

npm i --save formidable

Sau khi cài đặt xong mô-đun, bạn phải đưa nó vào chương trình

const formidable = require('formidable')

Mình chọn module ghê gớm bởi nó là một module khá phổ biến mà có vài điểm nổi bật như

Bài viết này đã được đăng tại [free tuts. bọc lưới]

  • Tốc độ khá nhanh (khoảng từ 900-2500MB/s) và phân tích dữ liệu ra nhiều luồng (sử dụng các luồng trong nodejs)
  • Tự động ghi file vào ổ đĩa (tại thời điểm mình viết bài này thì nó chưa hỗ trợ, bạn cần kết hợp module fs để ghi file)
  • Plugin API cho phép người dùng chỉnh sửa cách phân tích cú pháp công thức và các plugin hỗ trợ
  • Bộ nhớ ít hơn
  • Nhanh chóng bắt lỗi
  • Nhiều phương thức cho công việc test

2. Build page upload file sử dụng Nodejs

Mình sẽ chia cấu trúc thư mục của dự án thành 3 phần như sau

  • xemUploadForm. html. here is used file to contain the web interface
  • mục lục. js. tệp chứa các đoạn mã xử lý của máy chủ
  • /tải lên. thư mục chứa các tập tin

Build giao diện trang upload

Mình sẽ sử dụng framework Bootstrap 4 để xây dựng giao diện một cách nhanh hơ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;
    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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
9 diẽ có nội dung như sau




    
    
    Upload file using NodeJS
    


    

Upload file using nodejs - Freetuts.net


Ở đây mình sẽ tạo một form upload có action="/upload" mà method là POST, thuộc tính enctype="multipart/form-data" chỉ định form sẽ mất mã hóa

Build HTTP Web Server

Bạn cần xây dựng Máy chủ web HTTP để xử lý các yêu cầu từ người dùng, cụ thể trong dự án này là tệp tải lên. Để khởi động, bạn phải sử dụng mô-đun HTTP có trong Nodejs. Nếu bạn chưa biết cách khởi tạo HTTP Web Server mời bạn đọc bài viết cách khởi tạo HTTP Web Server trong NodeJS mà mình đã viết trong seri này trước đó

In file

var formidable = require('formidable');
0 ta process used http. createServer() to start up server

________số 8

Máy chủ sẽ lắng nghe ở cổng 6969 và trả về biểu mẫu tải lên. Vì giao diện của trang web nằm trong tệp

var formidable = require('formidable');
1 nên để lấy tệp nội dung đó mình phải sử dụng mô-đun fs của NodeJS để đọc

Xử lý yêu cầu tải tệp lên từ người dùng

Khi upload file người dùng sẽ gửi một phương thức request mới là POST, việc cần làm bây giờ là sử dụng module formdable để phân tích cú pháp form. Trong phần kiểm tra điều kiện người dùng đã tải tệp lên máy chủ, bạn sẽ xử lý tệp tải lên như sau

//Khởi tạo API formidable
    const form = new formidable.IncomingForm();
    //Tiến hành parse form
    form.parse(req, function (err, fields, files) {
      //Lấy đượng dẫn tạm thời của  file khi upload
      let oldPath = files.files.path
      //Đường dẫn mới khi upload 
      let newPath = __dirname + '/uploads/' + files.files.name
      //Tiến hành rename file tạm thời thành đường dẫn file mới
      fs.rename(oldPath, newPath, (err) => {
         //Trả ra lõi nếu gặp
         if (err) return res.end(err)

         //Trả về kết quả thành công
         return res.end('

Upload success !

') }) })

Trước tiên bạn phải khởi tạo API IncomingForm() để ghê gớm biết rằng có biểu mẫu gửi, sau đó sử dụng biểu mẫu hàm. parse() để phân tích yêu cầu của khách hàng gửi về lúc này hàm sẽ trả về một cuộc gọi lại bao gồm các giá trị khi biểu mẫu đã được phân tích cú pháp. Việc bạn cần làm bây giờ là đổi tên tệp bằng mô-đun fs

Mô-đun ghê gớm còn cho phép bạn thêm một số tùy chọn, bạn có thể truyền 1 đối tượng chứ không phải các tinh chỉnh vào hàm

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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
0

Chúng ta có thể tinh chỉnh một số giá trị như

  • tùy chọn. mã hóa {chuỗi} - Mặc định 'utf-8', tinh chỉnh kiểu mã hóa tại các trường ở dạng
  • tùy chọn. uploadDir {string} - Đường dẫn mặc định khi tải tệp lên, bạn có thể chỉnh sửa sau đó sử dụng fs. đổi tên(). Default will be os. tmpdir()
  • tùy chọn. keepExtensions {boolean} - default is false, has rest section
  • tùy chọn. maxFileSize {number} - default 200 * 1024KB = 200MB, giới hạn tệp tải lên tối đa
  • tùy chọn. maxFields {số} - mặc định 1000;
  • tùy chọn. maxFieldsSize {number} - mặc định 20 * 1024 * 1024 (20mb); giới hạn bộ nhớ được sử dụng để phân tích cú pháp các trường (tệp ngoại trừ trường)
  • tùy chọn. hash {boolean} - default; . createHash để biết các thuật toán có sẵn
  • tùy chọn. bội số {boolean} - default; . parse, đối số tệp (của hàm gọi lại) sẽ chứa các mảng tệp cho các đầu vào để gửi nhiều tệp bằng cách sử dụng nhiều thuộc tính HTML5. Ngoài ra, các trường đối số sẽ chứa các mảng giá trị cho các trường có tên kết thúc bằng '[]'

Tập tin cuối cùng

var formidable = require('formidable');
0 khi hoàn thiện sẽ như sau

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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080);
1

Trên đây là những kiến ​​thức cơ bản về xử lý upload file trong Nodejs, thông thường khi xử lý upload file người ta sử dụng module Multer để hỗ trợ upload và module Express để khởi động server. Vì đây là bài viết nằm trong phần NodeJS cơ bản nên mình sẽ đề cập đến việc upload file bằng cách kết hợp giữa 2 module Multer và Express trong phần về Express framework. Mong bài viết này có thể giúp ích cho bạn trong việc lập trình với Nodejs, cảm ơn bạn đã quan tâm đến bài viết này