Nodejs 文件上傳

node js 接收表單數(shù)據(jù)原理

/**
 * node js 接收表單數(shù)據(jù)
 */
const http = require("http");
const qs   = require("querystring");

http.createServer((request, response) => {
    // 表單提交的原理
    if (request.url === "/post" && request.method.toLowerCase() === "post") {
        // 1. 設置接收的變量
        let formData = "";

        // 2. 接收小段數(shù)據(jù)
        request.on("data", buf => {
            formData += buf;
        });

        // 3. 監(jiān)聽所有數(shù)據(jù)傳遞完畢事件
        request.once("end", () => {
            formData = qs.parse(formData);
            console.log(formData); // object
            console.log("數(shù)據(jù)接收完成");
        });
    }
}).listen(3000);

使用 formidable 上傳文件

/**
 * 使用formidable上傳圖片
 */
const http = require("http");
const fs   = require("fs");
const formidable = require("formidable");
const uuidv1 = require("uuid/v1");
const path = require("path");

http.createServer((request, response) => {
    if (request.url == "/") {
        fs.readFile(__dirname+"/index.html", (err, data)=>{
            if (err) {throw err;}
            response.setHeader("content-type", "text/html;charset=utf8;");
            response.end(data.toString());
        });
    }

    if (request.url === "/post" && request.method.toLowerCase() === "post") {
        // 1.實例化對象
        const form = new formidable();
        // 2.設置文件上傳的路徑, 默認就會自動上傳到這個目錄中,這個目錄必須要存在,否則報錯, 不建議使用相對路徑
        form.uploadDir = __dirname + '/uploads';


        // 3.獲取表單內(nèi)容
        form.parse(request, (err, fields, files)=> {
            /****************** 利用formidable的文件名
            // 3.1 獲取原文件名
            let ext     = path.extname(files.file.name);
            // 3.2 獲取上傳文件的路徑
            let oldPath = files.file.path;
            // 3.3 拼接新路徑
            let newPath = oldPath + ext;
            console.log(newPath);
            // 3.4 修改文件名
   
            或者使用 uuid 這個包, 二選一
            ************************************/
            // 3.1 獲取獨一無二的一個字符串 uuid 
            let uuid = uuidv1();
            // 3.2 獲取上傳文件的后綴
            let ext = path.extname(files.file.name);
            // 3.3 獲取路徑
            let oldPath = files.file.path;
            let newPath = __dirname + "/uploads/" + uuid + ext;
            // 3.4 修改文件名
            
            fs.rename(oldPath, newPath, err=>{
                if (err) throw err;
                response.end("文件上傳成功");
            });
            response.end("images");
        });
    }
    // response.end("404");
}).listen(3000);
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容