req.file 使用 multer 上传时未定义

问题描述 投票:0回答:1

我有以下代码

router.post("/author-image/:id", async (req, res) => {
    const upload = await Common.upload(req, res);

    try {
        await Events.addAuthorImg(req.params.id, upload);

        return res.json({
            status: "ok"
        });

    } catch (error) {
        console.dir(error);

        return res.json({
            status: "error",
            error: "Unable to process your request. Please try again later."
        });
    }
});

// Common.js

const _ = require("underscore");
const UPLOAD_FILE_SIZE_LIMIT = 1024 * 1024 * 40;
const ALLOWED_FILE_TYPES = [".png", ".jpg", ".jpeg", ".gif", ".mp3", ".pdf"];
const UPLOAD_FILE_DIR = "./client/public/uploads/";
const multer = require("multer");
const tinify = require("../tinify");
const s3 = require("../s3");
var Q = require('q');
const path = require("path");
const util = require("util");
const fs = require("fs");
const unlinkFile = util.promisify(fs.unlink);

const generateRandomId = (length) => {
    var result = "";
    var characters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
};

const upload = multer({
    storage: multer.diskStorage({
        destination: (req, file, callBack) => {
            callBack(null, UPLOAD_FILE_DIR); // './public/images/' directory name where save the file
        },
        filename: (req, file, callBack) => {
            callBack(
                null,
                generateRandomId(8) + Date.now() + path.extname(file.originalname)
            );
        },
    }),
    fileFilter: function (req, file, callback) {
        var ext = path.extname(file.originalname);
        console.dir(file.path);
        if (ALLOWED_FILE_TYPES.indexOf(ext) === -1) {
            return callback("Only images are allowed.");
        }
        callback(null, true);
    },

    limits: {
        fileSize: UPLOAD_FILE_SIZE_LIMIT,
    },
});

module.exports = {

    upload: async (req, res) => {
        var defer = Q.defer();
        const uploadSingle = upload.single("file");

        uploadSingle(req, res, async (err) => {
            if (err) {
                if (err instanceof Error) {
                    err = err.message;
                }
                defer.reject(err);
            }
            console.dir(req.file);
            if (!req.file) {
                defer.reject("Please provide a file to upload.");
            } else {
                const result = await s3.process(
                    req.file,
                    process.env.AWS_ACCESS_KEY_ID,
                    process.env.AWS_SECRET_ACCESS_KEY,
                    process.env.AWS_BUCKET_REGION,
                    process.env.S3_BUCKET
                );
                // You may apply filter, resize image before sending to client

                // Deleting from local if uploaded in S3 bucket
                await unlinkFile(req.file.path);
                defer.resolve(result.Location);
            }
        });
        return defer.promise;
    }
};

我收到一个错误,指出 req.file 未定义。有人可以帮忙吗?

表格如下:

<form onSubmit={(ev) => this.handleSubmit(ev)} name="form" method="POST" enctype="multipart/form-data">
    <input type="text" name="name" />
</form>
reactjs node.js multer
1个回答
0
投票

您似乎没有从前端表单发送任何文件

<form onSubmit={(ev) => this.handleSubmit(ev)} name="form" method="POST" enctype="multipart/form-data">
   <input type="file" name="name" /> /* change the type attr to `file` type then try it*/
</form>
© www.soinside.com 2019 - 2024. All rights reserved.