Front-end_dev
파일 업로드 및 다운로드 본문
템플릿 소스코드
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 | <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form method='post' action='/' enctype='multipart/form-data'> <p> <input type='file' name='file' onchange='complete(this)'> </p> <p> <input type='submit' value='upload'> </p> </form> <h1 id='progress'>파일이 다 올라갈 때 까지 기다려 주세요.</h1> </body> <script> progress = document.querySelector('#progress'); function complete() { progress.innerHTML = '파일을 정상적으로 올렸습니다. upload를 클릭해주세요.'; } </script> </html> | cs |
서버 소스코드
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | const http = require('http'); const fs = require('fs'); const express = require('express'); const formidable = require('formidable'); const app = express(); const server = http.createServer(app); app.post('/', (req,res) => { upload(req,res); }); app.get('/', (req,res) => { show(req,res); }) function show(req,res) { const buffer = fs.readFileSync('./FileUploadHtml.html'); res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Length', Buffer.byteLength(buffer)); res.end(buffer); } server.listen(3131,() => { console.log('server is started'); }) function upload(req,res) { if(!isFormData(req)) { res.statusCode = 400; res.end('Bad request\n'); return; } else { const form = new formidable.IncomingForm(); form.uploadDir = __dirname + '/FileStore'; form.encoding = 'utf-8'; form.parse(req, (err, fields, files) => { const name = files.file.name; const path = files.file.path; const type = name.slice(name.indexOf('.')+1); console.log(type); let read; let output; res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(`<a href=${path}> ${name} </a>`); app.get(path, (req,res) => { read = fs.createReadStream(path); output = fs.createWriteStream(path + '.' + type); read.pipe(output); res.download(path + '.' + type); }) }); form.on('progress', (byteRecived, byteExpected) => { const percent = Math.floor(byteRecived / byteExpected * 100); console.log(percent); }) } } function isFormData(req) { const type = req.headers['content-type'] || ''; return 0 == type.indexOf('multipart/form-data'); } | cs |
결과화면