簡體   English   中英

TypeError:無法使用 nodejs 讀取未定義的屬性“byteLength”

[英]TypeError: Cannot read property 'byteLength' of undefined with nodejs

我無法理解為什么 firebase 不接受圖像,出現以下消息: TypeError: Cannot read property 'byteLength' of undefined

我試圖將 'byteLength' 值添加到我的對象 (req.file) 但同樣的錯誤繼續存在。

下面是我的實現

const firebase2 = require('firebase/app');
require('firebase/storage');


router.put('/addimage', multer.single('picture'), async (req, res, next) => {
   const newName = uuidv1() + "-" + req.file.originalname;
   var storageRef = firebase2.storage().ref('photo/'+ newName);
   storageRef.put(req.file);  
});

在此處輸入圖像描述

這個 html 示例我確實有效。 我想做一個后端所以我正在遷移到 nodejs

<html>
<head>
    <meta charset="utf-8">
    <title>Teste</title>
    <style>
        body {
            display: flex;
            min-height: 100vh;
            width: 100%;
            padding: 0;
            margin: 0;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        #uploader {
            -webkit-appearance: none;
            appearance: none;
            width: 50%;
            margin-bottom: 10%;
        }
    </style>
</head>
<body>
    <progress value="0" max="100" id="uploader">0%</progress>
    <input type="file" value="upload" id="fileButton"></input>

    <script src="https://gstatic.com/firebasejs/live/3.0/firebase.js"></script>
    <script>
        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        var firebaseConfig = {
          apiKey: "xxxxx",
          authDomain: "xxxxx",
          projectId: "xxxxx",
          storageBucket: "xxxxxxx",
          messagingSenderId: "xxxxxx",
          appId: "xxxxxxx",
          measurementId: "xxxxxx"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);

        var uploader = document.getElementById('uploader');
        var fileButton = document.getElementById('fileButton');

        fileButton.addEventListener('change', function(e){

            var file = e.target.files[0];

            var storageRef = firebase.storage().ref('sweet_fifs/'+ file.name);

            var task = storageRef.put(file);

            task.on('state_changed', 
                function progress(snapshot) {
                    var percetage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                    uploader.value = percetage;
                },
                function error(err) {

                }
            )

        });
        
      </script>
</body>

Reference#put方法需要一個Blob | Uint8Array | ArrayBuffer Blob | Uint8Array | ArrayBuffer Blob | Uint8Array | ArrayBuffer作為第一個參數。 您提供的req.file object 不是這些。 但是,我們可以看到有一個Buffer object 可用作req.file object 的屬性,並且可以說該緩沖區中的內容類型也是如此。 所以我們需要做的就是提取這些值並將它們傳遞給Reference#put() 也不要忘記為用戶創建響應並處理任何錯誤。

router.put('/addimage', multer.single('picture'), async (req, res, next) => {
   const newName = uuidv1() + "-" + req.file.originalname;
   const storageRef = firebase2.storage().ref('photo/'+ newName);
   
   storageRef.put(req.file.buffer, {
     contentType: req.file.mimetype
   })
   .then(() => storageRef.getDownloadURL()) // after upload, obtain the download URL
   .then(
     (url) => {
       // persisted to storage successfully and obtained download URL
       res
         .status(201)
         .set("Content-Location", url) // use "Location" if you want to redirect to it
         .json({
           "message": "Upload successful"
         });
     },
     (err) => {
       // failed to save to storage
       logger.error({
         message: "Upload failed with error",
         errorMessage: err.message,
         errorStack: err.stack
       });

       res
         .status(500)
         .json({
           "message": "Upload failed",
           "error": err.code || "unknown"
         });
     }
   )
   .catch((err) => {
     // if here, something has gone wrong while sending back the response
     // likely a syntax error, or sending responses multiple times
     logger.error({
       message: "Unexpected rejection during /addImage",
       errorMessage: err.message,
       errorStack: err.stack
     });
   });
});

我無法理解為什么 firebase 不接受圖像,出現以下消息: TypeError: Cannot read property 'byteLength' of undefined

我試圖將 'byteLength' 值添加到我的對象(req.file),但同樣的錯誤繼續存在。

下面是我的實現

const firebase2 = require('firebase/app');
require('firebase/storage');


router.put('/addimage', multer.single('picture'), async (req, res, next) => {
   const newName = uuidv1() + "-" + req.file.originalname;
   var storageRef = firebase2.storage().ref('photo/'+ newName);
   storageRef.put(req.file);  
});

在此處輸入圖像描述

這個 html 示例我確實有效。 我想做一個后端,所以我正在遷移到 nodejs

<html>
<head>
    <meta charset="utf-8">
    <title>Teste</title>
    <style>
        body {
            display: flex;
            min-height: 100vh;
            width: 100%;
            padding: 0;
            margin: 0;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        #uploader {
            -webkit-appearance: none;
            appearance: none;
            width: 50%;
            margin-bottom: 10%;
        }
    </style>
</head>
<body>
    <progress value="0" max="100" id="uploader">0%</progress>
    <input type="file" value="upload" id="fileButton"></input>

    <script src="https://gstatic.com/firebasejs/live/3.0/firebase.js"></script>
    <script>
        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        var firebaseConfig = {
          apiKey: "xxxxx",
          authDomain: "xxxxx",
          projectId: "xxxxx",
          storageBucket: "xxxxxxx",
          messagingSenderId: "xxxxxx",
          appId: "xxxxxxx",
          measurementId: "xxxxxx"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);

        var uploader = document.getElementById('uploader');
        var fileButton = document.getElementById('fileButton');

        fileButton.addEventListener('change', function(e){

            var file = e.target.files[0];

            var storageRef = firebase.storage().ref('sweet_fifs/'+ file.name);

            var task = storageRef.put(file);

            task.on('state_changed', 
                function progress(snapshot) {
                    var percetage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                    uploader.value = percetage;
                },
                function error(err) {

                }
            )

        });
        
      </script>
</body>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM