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ó Show 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
Tạo một thư mục “tải lên tệp jtp” có các tệp sau 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 Tập tin. mục lục. html Tập tin. người phục vụ. js 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
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(''); 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(''); 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(''); 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(''); 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(''); 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(''); 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(''); 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(''); return res.end(); } }).listen(8080);8) Thử nghiệmChạy tệp var formidable = require('formidable');0 Truy cập url var formidable = require('formidable');1 sẽ thấy giao diện tải lên tệp Ở đây mình thực hiện upload file var formidable = require('formidable');2 Kết quả 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 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ớmCó 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]
2. Build page upload file sử dụng NodejsMình sẽ chia cấu trúc thư mục của dự án thành 3 phần như sau
Build giao diện trang uploadMì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(''); return res.end(); } }).listen(8080);9 diẽ có nội dung như sau
Ở đâ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 ServerBạ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ùngKhi 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(' 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(''); return res.end(); } }).listen(8080);0 Chúng ta có thể tinh chỉnh một số giá trị như
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(''); 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 |