با عرض سلام و وقت بخیر خدمت کاربران سایت پی وی لرن ، با یکی دیگر از جلسات دوره کامل آموزش Node.js در خدمت شما دوستان هستیم. در این جلسه قصد داریم به آموزش آپلود فایل در Node.js ( ساخت یک فرم آپلود ، تجزیه فایل آپلود شده ، ذخیره فایل ) بپردازیم.
از ماژول Formidable برای آپلود فایل در node.js استفاده می کنیم.
این ماژول داخل خود node.js نیست و باید آن را دانلود کنیم:
C:\Users\Your Name>npm install formidable |
در ادامه به مراحل چگونگی آپلود فایل خواهیم پرداخت.
یک فایل node.js ایجاد می کنیم که یک فرم HTML با یک فیلد آپلود بسازد:
1 2 3 4 5 6 7 8 9 10 | 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); |
ماژول formidable را وارد برنامه کنید. از این ماژول برای تجزیه (parse) کردن فایل آپلود شده استفاده می کنیم.
وقتی که فایل آپلود و تجزیه شد، در پوشه temporary روی کامپیوتر/سرور شما قرار می گیرد.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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); |
هنگامی که فایل با موفقیت در سرور آپلود شود، در فولدر temporary قرار می گیرد.
این مسیر دایرکتوری توسط شی files قابل دسترس است.
این شی سومین پارامتر در تابع callback متد ()parse است.
برای انتقال فایل به مسیر دلخواه از ماژول fs یا همان فایل سیستم استفاده می کنیم و نام فایل را تغییر می دهیم:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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(8080); |
جلسه آپلود فایل در node.js نیز به پایان رسید.
در جلسه بعد به آموزش ارسال ایمیل با node.js خواهیم پرداخت. با ما همراه باشید.