1. 程式人生 > >使用NodeJS實現檔案上傳到自定義資料夾

使用NodeJS實現檔案上傳到自定義資料夾

準備工作

## 首先要安裝一個NodeJS

## 建立一個資料夾存放操作檔案上傳的程式碼

## 這裡上傳操作需要用到第三方包:multiparty
## 在建立的資料夾裡黑窗安裝    :  npm install multiparty --save

開始書寫程式碼

1.先生成專案的描述檔案 package.json :---------------------切換到專案根目錄: 在黑窗中執行 npm init -y

2.把上傳檔案的html頁面程式碼寫好,直接上圖:

<form action="/postload" enctype="multipart/form-data" method="post">
        <input type="text" name="nickname"><br>
        <input type="text" name="sex"><br>
        <input type="file" name="upload1" multiple="multiple"><br>
        <input type="file" name="upload2" multiple="multiple"><br>
        <input type="submit" value="提交">
</form>

3.開始書寫js程式碼 -----分為四大步驟:

------- *1.匯入模組
------- *2.建立服務
------- *3.請求,處理,響應
------- *4.開啟web 服務

1.匯入模組

const http = require('http')
const fs = require('fs')
const path = require('path')

// 以下是第三方包需要匯入的
const multiparty = require('multiparty');
const util = require('util');

// 這是獲取時間的第三方包
const format = require('date-format');

2.建立服務

var server = http.createServer();
3.請求,處理,響應

這裡需要傳送兩次請求:

server.on('request',function(req,res){  
 	處理程式碼
})

1.讓使用者看到上傳檔案的頁面

if(urlstr.includes('uploadPage.html')){
        fs.readFile(path.join(__dirname,"html/uploadPage.html"),(err,data)=>{
            if(err){
                console.log(err);             
            }else{
                res.setHeader('Content-Type','text/html;charset=utf-8')
                res.end(data)
            }
        })
 }

2.當用戶點選提交按鈕,跳到指定頁面:/postload,完成檔案上傳 --------分為兩步: (1)建立一個資料夾 (2)使用第三方包multiparty的方法,進行檔案上傳 第三方包網址:https://www.npmjs.com/package/multiparty

else if(urlstr.includes('/postload') && req.method === 'POST'){

	    //建立一個名字叫做upload的資料夾,路徑為:uploadDir 
        const uploadDir = path.join(__dirname,"upload") 
        const exists = fs.existsSync(uploadDir)
        
        // 判斷是否存在
        if(!exists){
            const err = fs.mkdirSync(uploadDir)
            if(err){
                console.log(err);           
            }else{
                console.log('mkdir ok');              
            }
        }else{
            console.log('已經存在!!!');       
        }

		//第三方包的方法
        const form = new multiparty.Form({uploadDir});
        form.parse(req, function(err, fields, files) {
        
            // 文字域:fields
            // 檔案域:files
            // Object.keys(data):將物件中的 key/value 變成一個數組可以遍歷
            Object.keys(fields).forEach(key=>{
                console.log(`key is ${key}`);
                console.log(`value is ${fields[key][0]}`);
                
            })
            Object.keys(files).forEach(key=>{
                console.log(`key is ${key}`);
                // console.log(files[key][0]);   

                // 獲取檔案的完整路徑
                const oldPath = files[key][0].path
                
                //使用第三包format,用獲取到的時間對檔案重新命名
                const newPath = path.join(__dirname,"upload",`${format('yyyy-MM-dd-hh-mm-ss-SSS', new Date())}.txt`)
                const err = fs.renameSync(oldPath, newPath)
                if(err){
                    console.log(err);               
                }else{
                    console.log('rename ok');               
                }  
            })
            res.writeHead(200, {'content-type': 'text/plain;charset=utf-8'});
            res.write('received upload:\n\n');
            res.end(util.inspect({fields: fields, files: files}));
        });
 
        return;
    }else{
        res.end('')
    }

4.開啟web 服務

server.listen(8899,'127.0.0.1',function(err){
    if(err){
        console.log(err);     
    }else{
        console.log('start ok');      
    }
})
本文共用到兩個第三方包:

multiparty 和format

使用方法:
	1.安裝:npm i xxx --save
	2.導包:const  xxx = require('xxx')
	3.檢視第三方包的文件,使用作者說的方法
本文用到有關檔案操作的一些方法
 1.檔案操作一般需要用到2個模組:fs(檔案操作)和path(獲取路徑)
 2.獲取檔案路徑:__dirname
 3.拼接檔案路徑:path.join(__dirname,'html/index.html')
 ## 以下是用的都是同步的方法,(本文用的也是同步的方法,考慮到檔案上傳是非同步操作,故再上傳之前需要,將資料夾建立好)
 4.讀取檔案路徑:const content = fs.readFileSync(filePath)
 5.建立資料夾:fs.mkdirSync(path[, options])
 6.判斷檔案是否存在:fs.existsSync(path)
 7.檔案重新命名:fs.renameSync(oldPath, newPath)@[TOC](這裡寫自定義目錄標題)