English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Node.js 파일 업로드–이 Node.js 강의에서는 Web 클라이언트에서 파일을 Node.js 서버로 업로드하는 방법을 배웁니다. 다시 말해 클라이언트가 Node.js 서버로 파일을 업로드할 수 있습니다。
파일을 Node.js 서버에 업로드하려면 다음 단계별 가이드를 따라야 합니다:
이 예제에서는 http, fs, 강력 모듈을 사용합니다。http:서버 활동에 사용됩니다。노드 fs:업로드된 파일을 서버의 특정 위치에 저장합니다。강력:html 테이블 데이터를 해석합니다. 위의 모듈을 아직 설치하지 않았다면 즉시 NPM을 사용하여 설치할 수 있습니다. 터미널에서 다음 명령어를 실행하여 모듈을 설치합니다:
npm install http npm install fs npm install formidable |
다음과 같은 테이블을 포함한 HTML 페이지(upload_file.html)을 준비하세요. 파일 업로드와 폼 제출을 위한 입력 태그를 포함합니다.
<form action="fileupload" method="post" enctype="multipart/form-data"> <input type="file" name="filetoupload"> <input type="submit" value="Upload"> </form>
侦听 포트를 생성하세요8086HTTP 서버를 생성하고 (포트를 변경할 수 있습니다) 다음과 같이 두 URL에 서버를 제공합니다:
http.createServer(function (req, res) { if (req.url == '/uploadform') { // 요청 주소가 “ / uploadform” // HTML 파일을 포함한 업로드 테이블로 응답을 채우세요 } else if (req.url == '}}/fileupload') { // 요청 URL이 “ / fileupload” // 강력한 모듈 사용 // 读取表单数据(包括上载的文件) // 并将文件保存到一个位置。 ).listen(8086);
使用强大的模块,解析表单元素并将文件保存到某个位置。文件上传后,您可能会显示一条消息,说明文件上传成功。最初,文件被保存到一个临时位置。我们可以使用fs.rename()方法,使用新路径将文件移动到所需位置。
var form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files) { // oldpath: 파일이 저장된 일시적인 폴더 var oldpath = files.filetoupload.path; var newpath = upload_path + files.filetoupload.name; // 파일을 새 위치로 복사합니다 fs.rename(oldpath, newpath, function(err) { if (err) throw err; // 귀하는 다른 html 페이지를 사용하여 응답할 수 있습니다 res.write('File uploaded and moved!'); res.end(); }); });
以下是Node.js上传文件的完整工作示例
此示例有两个文件,如下所示:
upload_file.html
<!DOCTYPE html> <html> <head> <title>Upload File</title> <style> body{text-align:center;} form{display:block;border:1px solid black;padding:20px;} </style> </head> <body> <h1>Upload files to Node.js Server</h1> <form action="fileupload" method="post" enctype="multipart/form-data"> <input type="file" name="filetoupload"> <input type="submit" value="Upload"> </form> </body> </html
var http = require('http'); var fs = require('fs'); var formidable = require('formidable'); // 包含上传表单的html文件 var upload_html = fs.readFileSync("upload_file.html"); // 将其替换为保存上传文件的位置 var upload_path = "/home/arjun/워크스페이스/nodejs/upload_file/"; http.createServer(function (req, res) { if (req.url == '/uploadform') { res.writeHead;200); res.write(upload_html); return res.end(); } else if (req.url == '}}/fileupload') { var form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files) { // oldpath: 파일이 저장된 일시적인 폴더 var oldpath = files.filetoupload.path; var newpath = upload_path + files.filetoupload.name; // 파일을 새 위치로 복사합니다 fs.rename(oldpath, newpath, function(err) { if (err) throw err; // 귀하는 다른 html 페이지를 사용하여 응답할 수 있습니다 res.write('File uploaded and moved!'); res.end(); }); }); ).listen(8086);
노드를 가진 터미널에서 Node.js 스크립트 파일을 실행하세요
arjun@w3codebox:~/워크스페이스/nodejs/upload_file$ node nodejs-업로드-file.js
업로드된 파일은 node.js 파일 nodejs에 저장됩니다-업로드-file.js 옆. 이 위치를 node.js 스크립트 파일에서 변경할 수 있습니다。
웹 브라우저(HTTP 클라이언트)를 열고 해당 URL을 클릭하세요 http:// localhost:8086/uploadform
浏 览.
파일을 선택한 후 '열기'를 클릭하세요。
현재, 파일은 양식에 업로드되었습니다. Node.js의 Upload 버튼을 클릭하여 양식 요소를 분석하고 파일을 저장하세요。
Node.js 스크립트 파일 옆의 Node.js 서버를 확인하세요。
arjun@w3codebox:~/워크스페이스/nodejs/upload_file$ ls blur1.jpg nodejs-업로드-file.js upload_file.html
이 Node.js 강의에서 - Node.js에서 파일을 서버에 업로드,우리는 강력한 fs와 http 모듈을 사용하여 파일을 Node.js 서버에 업로드하는 방법을 배웠습니다。