node.js上传图片接口

node.js需要使用koa-multer库来实现上传图片接口。

实际上先通过koa-multer下载到本地指定目录,然后上传到阿里云(部分格式图片需要转换成网络格式图片jgp再上传)。

首先在系统启动文件引入注册路由:

复制代码
app.use(BodyParser({
    'formLimit':'3mb',
    'jsonLimit':'3mb',
    'textLimit':'3mb'
}));
// 注意顺序,必须body parser在前, router在后
app.use(router.routes());

// 1. 注册基础路由 注意顺序,必须body parser在前, router在后
const routes = require('./app/routes/index.js');
app.use(routes.routes());
app.use(routes.allowedMethods());

// 2. 初始化Main路由
const Main = require('./app/main_erp.js');
Main.init(router);

// 3. 将Main路由注册到Koa应用
app.use(router.routes());
app.use(router.allowedMethods());

注意:3. 将Main路由注册到Koa应用不能省,不然无法接收到接口传递过来的文件。

具体的图片的下载和上传代码:

复制代码
const ImageTool = require('@app/tools/image_tool.js');
var Main = {};

// 处理图片
const fs = require('fs');
const path = require('path');

// 上传处理
const Multer = require('koa-multer');
const IMAGE_PATH = 'upload/image';
// 存储位置
let image_storage = Multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, IMAGE_PATH);
    },
    filename: function (req, file, cb) {
        //cb(null, Date.now() + '_' + makeid(6) + path.extname(file.originalname));
        cb(null, file.originalname);
    }
});
const ImageUploader = Multer({
    storage: image_storage,
    limits: {
        fileSize: 50 * 1024 * 1024 // 50MB限制
    }
});

async function dealImg(ctx) {
    // 获取文件扩展名
    const fileExt = path.extname(ctx.req.file.originalname).toLowerCase();
    
    // 支持的格式,直接上传原文件
    const readStream = fs.createReadStream(ctx.req.file.path);
    let arr = ctx.req.file.path.split('/');
    let filename = '/img/' + arr[arr.length - 1];
    //上传图片到阿里云
    return ImageTool.uploadImage(filename, fileExt, readStream, null, ctx.req.file.path);
}

/**
 * 路由
 * @param {*} router 
 */
function createRouteMap(router) {
    // 图片上传接口
    // 特殊接口,由于依赖Muler, 必须单独定义
    router.post('/api/uploadImage', ImageUploader.single('pic'), async (ctx, next) => {
        ctx.body = await dealImg(ctx);
    });
}

Main.init = function(router) {
    console.log('Main');
    // console.log('router:', router);
    createRouteMap(router);
};

module.exports = Main;
相关推荐
见过夏天1 天前
Node.js 常用命令全攻略
node.js
前端双越老师2 天前
我从 0 开发的 AI Agent 智语项目发布了
前端·node.js·agent
kyriewen2 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
donecoding3 天前
3 条命令搞定闭环 Monorepo:Lerna 版本管理 + 拓扑构建 + 自定义分发
前端·前端框架·node.js
Flynt4 天前
npm v12 来了:allowScripts 默认关闭,我的项目差点跑不起来
安全·npm·node.js
叫我Paul就好5 天前
尝试 Node 搭建后端-开发框架
node.js
风止何安啊6 天前
网课倍速痛点解决:一套前端代码实现自由控速播放器
前端·javascript·node.js
糖拌西瓜皮6 天前
Node.js核心模块实战:文件、路径、HTTP与流处理
javascript·node.js
糖拌西瓜皮6 天前
Node.js工程化实践:包管理、TypeScript配置与代码质量
typescript·node.js
糖拌西瓜皮6 天前
NestJS入门指南:Java开发者的Spring Boot体验
javascript·node.js