node.js接收前端上傳的文件並保存到其他位置+后端代碼支持進度條


一:直接上傳文件,放入body里

1.前端代碼

<input type="file" onchange="sendFiles(this.files)">
<script>
    function sendFiles(files) {
        const reader = new FileReader();
        const file = files[0];
        reader.readAsArrayBuffer(file);
        reader.onload = function (e) {
            fetch("http://127.0.0.1:3000/" + file.name, {
                method: 'post',
                body: e.target.result
            });
        };
    }
</script>

2.后端nodejs接受文件並保存

const http = require('http');
const fs = require('fs');
// 這個文件可以 把資料存放到file文件夾下
http.createServer(function (request, response) {
    response.setHeader('Access-Control-Allow-Origin', '*');
    // 下面的這個意思是放到這個路徑下,避免放到根目錄
    console.log(request.body)
    request.pipe(fs.createWriteStream('./file' + request.url, {
        //    encoding:'binary' // 行
        //    encoding:'base64' // 行
          encoding:'utf8' // 不知道為什么,這里怎么設置都不影響,
    }));
    response.end(`${request.url} done!`);
}).listen(3000);


二:上傳文件支持utf-8以及另存到file文件夾里+帶進度條

1.前端代碼

// 前端 upload.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>上傳文件demo</title>
    <style media="screen">
      .progress{
        width: 50%;
        height: 5px;
        border: 1px solid #ccc;
        border-radius: 4px;
        margin-top: 10px;
        position: relative;
      }
      .progress>span{
        display: inline-block;
        position: absolute;
        border-radius: 4px;
        top: 0;
        left: 0;
        height: 100%;
        width: 0;
        background-color: rgb(98, 230, 74);
        transition: width 0.3s ease-out;
      }
    </style>
  </head>
  <body>
    <input id="file" type="file" multiple>
    <div class="progress">
      <span></span>
    </div>
    <script type="text/javascript">
      var http = function (option) {
        // 過濾請求成功后的響應對象
        function getBody (xhr) {
          var text = xhr.responseText || xhr.response
          if (!text) {
            return text
          }

          try {
            return JSON.parse(text)
          } catch (err) {
            return text
          }
        }

        var xhr = new XMLHttpRequest();
        // 自定義 beforeSend 函數
        if(option.beforeSend instanceof Function) {
          if (option.beforeSend(xhr) === false) {
            return false
          }
        }

        xhr.onreadystatechange = function () {
          if (xhr.status === 200) {
            if (xhr.readyState === 4) {
              // 成功回調
              option.onSuccess(getBody(xhr))
            }
          }
        }

        // 請求失敗
        xhr.onerror = function (err) {
          option.onError(err)
        }

        xhr.open(option.type, option.url, true)

        // 當請求為上傳文件時回調上傳進度
        if (xhr.upload) {
          xhr.upload.onprogress = function (event) {
            if (event.total > 0) {
              event.percent = event.loaded / event.total * 100;
            }
            // 監控上傳進度回調
            if (option.onProgress instanceof Function) {
              option.onProgress(event)
            }
          }
        }

        // 自定義頭部
        const headers = option.headers || {}
        for (var item in headers) {
          xhr.setRequestHeader(item, headers[item])
        }

        xhr.send(option.data)
      }
	
	// 測試接口
      http({
        type: 'POST',
        url: 'http://127.0.0.1:3000/test',
        data: JSON.stringify({
          name: 'yolo'
        }),
        onSuccess: function (data) {
          console.log(data)
        },
        onError: function (err) {
          console.log(err)
        }
      })
      document.getElementById('file').onchange = function () {
        var fileList = this.files, formData = new FormData();
        Array.prototype.forEach.call(fileList, function (file) {
          formData.append(file.name, file)
        })
       // 當上傳的數據為 file 類型時,請求的格式類型自動會變為 multipart/form-data, 如果頭部格式有特定需求,在我的 http 函數中傳入 headers<Object> 即可,大家可自己查看,我這里沒有什么特殊處理所以就不傳了
        http({
          type: 'POST',
          url: 'http://127.0.0.1:3000/upload',
          data: formData,
          onProgress: function (event) {
            console.log(event.percent)
            document.querySelector('.progress span').style.width = event.percent + '%';
          },
          onSuccess: function (data) {
            console.log('上傳成功')
          },
          onError: function (err) {
            alert(err)
          }
        })
      }
    </script>
  </body>
</html>


2.后端代碼

// 上傳文件支持utf-8以及另存到file文件夾里+帶進度條
var express = require('express');
var path = require('path');
var fs = require('fs');
var app = express();
var bodyParser = require('body-parser');	// 過濾請求頭部相應格式的body
var multer = require('multer');
var chalk = require('chalk');	// 只是一個 cli 界面字體顏色包而已
var log = console.log.bind(console);

const cors=require('cors');
//跨域請求cors
app.use(cors
  (
    {
  // origin:"*" ,
  // origin:"http://localhost:8080" ,
  // origin:"http://10.22.12.12:4200" ,
  origin:"http://127.0.0.1:5500" ,
  credentials: true
}
)
);
app.use(express.static('static'));
// 接受 application/json 格式的過濾器
var jsonParser = bodyParser.json()
// 接受 application/x-www-form-urlencoded 格式的過濾器
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// 接受 text/html 格式的過濾器
var textParser = bodyParser.text()

// 自定義 multer 的 diskStorage 的存儲目錄與文件名
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'file') // 注意一下這里,這個是設置上傳到哪個文件夾的哦~~
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname)
  }
})

var upload = multer({ storage: storage })

// 頁面渲染
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'view/upload.html'));
})

app.post('/test', textParser, jsonParser, function (req, res) {
  log(req.body);
  var httpInfo = http.address();
  res.send({
    host: httpInfo.address,
    port: httpInfo.port
  })
})

// 對應前端的上傳接口 http://127.0.0.1:3000/upload, upload.any() 過濾時不對文件列表格式做任何特殊處理
app.post('/upload', upload.any(), function (req, res) {
  log(req.files)
  res.send({message: '上傳成功'})
})

// 監控 web 服務
var http = app.listen(3000, '127.0.0.1', function () {
  var httpInfo = http.address();
  log(`創建服務${chalk.green(httpInfo.address)}:${chalk.yellow(httpInfo.port)}成功`)
})


參考文章:https://blog.csdn.net/yolo0927/article/details/78523020


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM