Node.js 파일 업로드
Formidable 모듈
"Formidable"이라고 불리는 파일 업로드 작업을위한 매우 훌륭한 모듈이 있습니다.
Formidable 모듈은 NPM을 사용하여 다운로드하고 설치할 수 있습니다.
C:\Users\Your Name>npm install formidable
Formidable 모듈을 다운로드 한 후에는 해당 응용 프로그램에 모듈을 포함시킬 수 있습니다.
var formidable = require('formidable');
파일업로드
이제 사용자가 파일을 컴퓨터에 업로드 할 수있는 Node.js의 웹 페이지를 만들 준비가되었습니다.
1 단계 : 업로드 양식 만들기
업로드 필드가있는 HTML 양식을 작성하는 Node.js 파일을 만듭니다.
예
이 코드는 HTML 양식을 생성합니다.
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);
2 단계 : 업로드 된 파일 구문 분석
서버에 도달하면 업로드 된 파일을 구문 분석 할 수있는 Formidable 모듈을 포함하십시오.
파일을 업로드하고 파싱하면 컴퓨터의 임시 폴더에 저장됩니다.
예
파일이 업로드되어 임시 폴더에 저장됩니다.
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);
3 단계 : 파일 저장
파일이 서버에 성공적으로 업로드되면 임시 폴더에 저장됩니다.
이 디렉토리에 대한 경로는 parse()메소드의 콜백 함수 에서 세 번째 인수로 전달되는 "files"객체에서 찾을 수 있습니다 .
파일을 원하는 폴더로 이동하려면 파일 시스템 모듈을 사용하고 파일 이름을 다음과 같이 변경하십시오.
예
fs 모듈을 포함하고 파일을 현재 폴더로 이동하십시오.
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);
게시글 목록
| 번호 | 제목 |
|---|---|
| 16619 | |
| 16618 | |
| 16612 | |
| 16603 | |
| 16598 | |
| 16589 | |
| 16578 | |
| 16571 | |
| 16563 | |
| 16554 | |
| 16546 | |
| 16534 | |
| 16527 | |
| 16520 | |
| 16513 | |
| 16510 | |
| 16505 | |
| 16498 | |
| 16490 | |
| 16486 | |
| 16482 | |
| 16465 | |
| 16458 | |
| 16456 | |
| 16448 | |
| 16447 |
PHP
한글 초,중,종성 분리하기
3
|
| 16440 | |
| 16439 |
웹서버
nginx 설치시 보안
3
|
| 16438 | |
| 16430 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기