从REST API返回的图像始终显示为损坏

从REST API返回的图像始终显示为损坏,第1张

从REST API返回的图像始终显示为损坏

避免发送回base64编码的图像(多个图像+大文件+
大编码字符串=非常慢的性能)。我强烈建议创建
一个微服务,该微服务仅处理图像上传和任何其他与图像相关的
获取/发布/放置/删除请求。将其与主应用程序分开。

例如:

  • 我使用multer创建图像缓冲区
  • 然后使用Sharp或fs保存图像(取决于文件类型)
  • 然后,我将文件路径发送到控制器以保存到数据库中
  • 然后,前端在尝试访问时发出GET请求:
    http://localhost:4000/uploads/timestamp-randomstring-originalname.fileext

简单来说,我的微服务就像CDN一样,仅用于图像。


For example, a user sends a post request to

http://localhost:4000/api/avatar/create
with some Formdata:

It first passes through some Express middlewares:

libs/middlewares.js

...app.use(cors({credentials: true, origin: "http://localhost:3000" })) // allows receiving of cookies from front-endapp.use(morgan(`tiny`)); // logging frameworkapp.use(multer({        limits: { fileSize: 10240000, files: 1, fields: 1        },        fileFilter: (req, file, next) => { if (!/.(jpe?g|png|gif|bmp)$/i.test(file.originalname)) {     req.err = `That file extension is not accepted!`     next(null, false) } next(null, true);        }    }).single(`file`))app.use(bodyParser.json()); // parses header requests (req.body)app.use(bodyParser.urlenpred({ limit: `10mb`, extended: true })); // allows objects and arrays to be URL-enpred...etc

Then, hits the

avatars
route:

routes/avatars.js

app.post(`/api/avatar/create`, requireAuth, saveImage, create);

It then passes through some user authentication, then goes through my

saveImage
middleware:

services/saveImage.js

const createRandomString = require('../shared/helpers');const fs = require("fs");const sharp = require("sharp");const randomString = createRandomString();if (req.err || !req.file) {  return res.status(500).json({ err: req.err || `Unable to locate the requested file to be saved` })  next();}const filename = `${Date.now()}-${randomString}-${req.file.originalname}`;const filepath = `uploads/${filename}`;const setFilePath = () => { req.file.path = filepath; return next();}(/.(gif|bmp)$/i.test(req.file.originalname))    ? fs.writeFile(filepath, req.file.buffer, (err) => { if (err) {    return res.status(500).json({ err: `There was a problem saving the image.`});    next(); } setFilePath();        })    : sharp(req.file.buffer).resize(256, 256).max().withoutEnlargement().toFile(filepath).then(() => setFilePath())

If the file is saved, it then sends a

req.file.path
to my
create

controller. This gets saved to my DB as a file path and as an image path (the
avatarFilePath
or
/uploads/imagefile.ext
is saved for removal purposes and
the
avatarURL
or
[http://localhost:4000]/uploads/imagefile.ext
is saved
and used for the front-end GET request):

controllers/avatars.js (I’m using Postgres, but you can substitute for
Mongo)

create: async (req, res, done) => { try {     const avatarurl = `${apiURL}/${req.file.path}`;     await db.result("INSERT INTO avatars(userid, avatarURL, avatarFilePath) VALUES (, , )", [req.session.id, avatarurl, req.file.path]);     res.status(201).json({ avatarurl }); } catch (err) { return res.status(500).json({ err: err.toString() }); done();         }

Then when the front-end tries to access the

uploads
folder via
<imgsrc={avatarURL} alt="image" />
or
<imgsrc="[http://localhost:4000]/uploads/imagefile.ext" alt="image" />
, it gets
served up by the microservice:

libs/server.js

const express = require("express");const path = app.get("path");const PORT = 4000;//============================================================//// EXPRESS SERVE AVATAR IMAGES//============================================================//app.use(`/uploads`, express.static(`uploads`));//============================================================////============================================================//app.listen(PORT);

What it looks when logging requests:

19:17:54 INSERT INTO avatars(userid, avatarURL, avatarFilePath) VALUES ('08861626-b6d0-11e8-9047-672b670fe126', 'http://localhost:4000/uploads/1536891474536-k9c7OdimjEWYXbjTIs9J4S3lh2ldrzV8-android.png', 'uploads/1536891474536-k9c7OdimjEWYXbjTIs9J4S3lh2ldrzV8-android.png')POST /api/avatar/create 201 109 - 61.614 msGET /uploads/1536891474536-k9c7OdimjEWYXbjTIs9J4S3lh2ldrzV8-android.png 200 3027 - 3.877 ms


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5646489.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存