• 회원가입
  • 로그인
  • 구글아이디로 로그인

[basic] Node.js - Upload Files (파일 업로드)

2,370  

목차

  1. formidable 모듈
  2. 1단계: 파일 업로드 Form 생성
  3. 2단계: 업로드 된 파일을 구문 분석
  4. 3단계: 파일 저장

 

formidable 모듈

[정의]

 

파일 업로드 용 외장 모듈.

 


[다운로드]

 

CMD 모드 접속 후, 아래 파란색 명령어 입력.

C:\Users\사용자명>npm install formidable

 


[구문]

 

var formidable = require('formidable');

 

 

※ 예제: 사용자가 컴퓨터에 파일을 업로드 가능한 웹페이지 만들기.

※ 각 단계별로 소스 발전 과정 확인. (3단계 소스가 완성된 소스.)

 

1단계: 파일 업로드 Form 생성

 

※ 파일 업로드 용 Form 양식 포함하는 Node.js 파일 생성.

 


 

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단계: 파일 저장

 

파일이 서버에 성공적으로 업로드되면 임시 폴더에 저장됨.


임시 폴더 경로는 "files" 객체에서 찾을 수 있으며,

parse() 메서드 콜백 함수의 3번째 인수로 전달됨.

(예) form.parse(req, function (err, fields, files) {

 

임시 폴더에서 선택 폴더로 파일을 이동하려면,

fs (파일 시스템) 모듈 사용해 파일명을 변경함.

 


※ 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.filepath;

      var newpath = 'C:/Users/사용자명/' + files.filetoupload.originalFilename;

      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);

 

1. 위 소스를 C:\User\사용자명\hz.js 경로에 저장.

2. CMD 모드에서 C:\User\사용자명>node hz.js 입력.

3. http://localhost:8080/ 접속해 파일 업로드 테스트.

4. C:\User\사용자명\ 폴더에 파일에 존재하는지 체크.

 

PS. 만약 에러 난다면, 점검할 사항.

1. formidable 외장 모듈을 설치했는지 여부 체크.

2. 소스에서 사용자명 부분을 본인에 맞게 변경했는지 체크.



2021-12-03 (금) 10:15 2년전
form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/사용자명/' + files.filetoupload.name;

위에서 console.log(oldpath) , console.log(newpath) 로 찍어보니까 undefined 가 떠서, console.log(files)로 확인해봤습니다.

path 를 filepath, name을 originalFilename 으로 고쳐야 할 것 같습니다
 var oldpath = files.filetoupload.filepath;
 var newpath = 'C:/Users/사용자명/' + files.filetoupload.originalFilename;

덕분에 정말 배우고 따라가고 있어요!감사합니다
주소
     
     
2021-12-03 (금) 10:42 2년전
댓글 감사합니다. 확인 후 수정해 놓도록 하겠습니다.
PS. 해당 (빨간색) 에러 부분을 수정해 놓았습니다.
주소
분류 제목
basic Node.js - Home
basic Node.js - Intro (소개)
basic Node.js - Start (시작) - 사용 환경 구축
basic Node.js - Modules (모듈)
basic Node.js - HTTP Module (데이터 전송 모듈)
basic Node.js - File System Module (파일 시스템 모듈)
basic Node.js - URL Module (주소 처리 모듈)
basic Node.js - NPM (노드 패키지 관리자)
basic Node.js - Events (이벤트)
basic Node.js - Upload Files (파일 업로드) 2
basic Node.js - Email (이메일 보내기)
mysql Node.js - MySQL 설치・연결 + 쿼리 보내기
mysql Node.js - MySQL Create Database (DB 생성)
mysql Node.js - MySQL Create Table (테이블 생성) ※ Primary key 설정.
mysql Node.js - MySQL Insert Into (데이터 삽입)
mysql Node.js - MySQL Select From (데이터 선택)
mysql Node.js - MySQL Where (조건절)
mysql Node.js - MySQL Order By (정렬 순서)
mysql Node.js - MySQL Delete From (데이터 삭제)
mysql Node.js - MySQL Drop Table (테이블 삭제)
1/4
목록
찾아주셔서 감사합니다. Since 2012