【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (五):POST上传文件的设置

本项目旨在学习如何快速使用 nodejs 开发后端api,并为以后开展其他项目的开启提供简易的后端模版。(非后端工程师)
由于文档是代码写完之后,为了记录项目中需要注意的技术点,因此文档的叙述方式并非开发顺序(并非循序渐进的教学文档)。建议配合项目源码node-mongodb-template

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (一):项目简介及安装依赖

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (二):项目文件夹架构及路由的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (三):Cors的设置及.env文件的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (四):状态码的使用

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (五):POST上传文件的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (六):token的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (七):MongoDB的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (八):API说明(暂时完结,后续考虑将在线版mongoDB变为本地版)

POST上传文件的设置

使用依赖 Multer 上传文件,用于处理 multipart/form-data 类型的表单数据。

这里以创建一个product,表单中需要上传 productImage 为例。

  • 安装依赖

pnpm i --save multer

  • 引用依赖
//routers\products.js
const multer = require('multer');
  • 设置文件的存储storage

destination 文件的存储位置,在根目录中创建一个文件夹uploads

filename 文件的命名, 举例:2024-09-04T14:14:22.081Z11.jpeg

const storage = multer.diskStorage({
    destination: function(req,file,cb){
        cb(null,'./uploads/')
    },
    filename: function(req,file,cb){
        cb(null,new Date().toISOString() + file.originalname)
    },
});
  • 筛选文件fileFilter

文件类型为 png/jpeg

const fileFilter = (req,file,cb)=>{
    if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
        cb(null,true);
    }else{
        cb(null,false);
    }
};
  • 上传文件的全部设置 Options

multer(options)

//fileSize文件大小设置
const upload = multer({
    storage: storage,
    limits:{
        fileSize:1024*1024*5
    },
    fileFilter: fileFilter
});
  • 读取文件

upload.single('fieldname') 接受一个以 fieldname 命名的文件。这个文件的信息保存在 req.file

router.post('/',upload.single('productImage'),(req,res,next) => {
    const product = new Product({
        _id:new mongoose.Types.ObjectId(),
        name:req.body.name,
        price:req.body.price,
        productImage:req.file.path
    });
    product
        .save()
        .then(result=>{
            res.status(201).json({
                message:'Create product successfully' ,
                createdProduct: {
                    result: result,
                    request:{
                        type: 'GET',
                        url: 'http://localhost:3000/products/'+result._id
                    }
                }
            });
        })
        .catch(err=>{
            res.status(500).json({
                error:err
            });
        });

});
  • postman中上传文件

Body的格式修改成 form-data

Key: productImage,并格式设置为File

Value: 选择文件

posted @ 2024-10-24 10:03  Sitar  阅读(2)  评论(0编辑  收藏  举报