NodeJS Typescript 'req.file'可能是'undefined'

eyh26e7m  于 2023-05-17  发布在  Node.js
关注(0)|答案(2)|浏览(165)
import express, { Router } from "express";
import { initializeApp } from "firebase/app";
import { getStorage, ref, getDownloadURL, uploadBytesResumable } from "firebase/storage";
import multer from "multer";
import config from "/home/rizki/herbal66-laravel/express/firebase.config"

const router: Router = express.Router();

//Initialize a firebase application
initializeApp(config.firebaseConfig);

// Initialize Cloud Storage and get a reference to the service
const storage = getStorage();

// Setting up multer as a middleware to grab photo uploads
const upload = multer({ storage: multer.memoryStorage() });

router.post("/", upload.single("filename"), async (req, res) => {
    try {
        const dateTime = giveCurrentDateTime();

        const storageRef = ref(storage, `files/${req.file.originalname + "       " + dateTime}`);

        // Create file metadata including the content type
        const metadata = {
            contentType: req.file.mimetype,
        };

        // Upload the file in the bucket storage
        const snapshot = await uploadBytesResumable(storageRef, req.file.buffer, metadata);
        //by using uploadBytesResumable we can control the progress of uploading like pause, resume, cancel

        // Grab the public url
        const downloadURL = await getDownloadURL(snapshot.ref);

        console.log('File successfully uploaded.');
        return res.send({
            message: 'file uploaded to firebase storage',
            name: req.file.originalname,
            type: req.file.mimetype,
            downloadURL: downloadURL
        })
    } catch (error) {
        return res.status(400).send(error.message)
    }
});

const giveCurrentDateTime = () => {
    const today = new Date();
    const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
    const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    const dateTime = date + ' ' + time;
    return dateTime;
}

export default router;

错误5条

const storageRef = ref(storage,files/${req.file.originalname +““+ dateTime});” const metadata = { contentType:}; document. writeln;”
const snapshot = await uploadBytesResumable(storageRef,req.file.buffer,metadata);”name:req.file.originalname, type:req.file.mimetype,`

我安装了一些包,如:

npm i @types/express
npm install dotenv
npm i @types/multer --save-dev
npm install typescript
但还是不起作用。。

eivnm1vs

eivnm1vs1#

我认为你需要在输入中指定req的数据类型,这样TypeScript就可以知道req.file是否有效。
你应该像这样将类型添加到req(以及你可以添加的所有其他const或var):

router.post("/", upload.single("filename"), async (req: {file: File} , res) => {

检查Typescript Documentation以查看有关变量类型的更多信息。

j2datikz

j2datikz2#

根据类型,这是正确的。您可以禁用严格的null检查,如果您不是100%肯定它将被定义,则使用optional chaining operator,或者使用非nullAssert操作符来告诉TypeScript不要担心它。

相关问题