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

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

我正在使用React为艺术作品集应用程序构建内容管理系统。客户端将POST到使用Mongoose插入MongoDB的API。然后,API在DB中查询新插入的图像,并将其返回给客户端。

这是使用Mongoose连接到MongoDB的代码:

mongoose.connect('mongodb://localhost/test').then(() => 
console.log('connected to db')).catch(err => console.log(err))

mongoose.Promise = global.Promise

const db = mongoose.connection

db.on('error', console.error.bind(console, 'MongoDB connection error:'))

const Schema = mongoose.Schema;

const ImgSchema = new Schema({
  img: { data: Buffer, contentType: String }
})

const Img = mongoose.model('Img', ImgSchema)

我正在使用multer和fs来处理图像文件。我的POST端点如下所示:

router.post('/', upload.single('image'), (req, res) => {
  if (!req.file) {
    res.send('no file')
  } else {
    const imgItem = new Img()
    imgItem.img.data = fs.readFileSync(req.file.path)
    imgItem.contentType = 'image/png'
    imgItem
      .save()
      .then(data => 
        Img.findById(data, (err, findImg) => {
          console.log(findImg.img)
          fs.writeFileSync('api/uploads/image.png', findImg.img.data)
          res.sendFile(__dirname + '/uploads/image.png')
        }))
  } 
})

我可以在文件结构中看到writeFileSync正在将映像写入磁盘。 res.sendFile抓住它并将其发送给客户端。

客户端代码如下所示:

handleSubmit = e => {
    e.preventDefault()
    const img = new FormData()
    img.append('image', this.state.file, this.state.file.name)
    axios
      .post('http://localhost:8000/api/gallery', img, {
        onUploadProgress: progressEvent => {
          console.log(progressEvent.loaded / progressEvent.total)
        }
      })
      .then(res => {
        console.log('responsed')
        console.log(res)
        const returnedFile = new File([res.data], 'image.png', { type: 'image/png' })
        const reader = new FileReader()
        reader.onloadend = () => {
          this.setState({ returnedFile, returned: reader.result })
        }
        reader.readAsDataURL(returnedFile)
      })
      .catch(err => console.log(err))
  }

这确实成功地将返回的文件和img数据url置于状态。但是,在我的应用程序中,图像始终显示为已损坏。

这是一些截图:

correct file is written to disk on server

file is returned from API and placed on application state

returned image is always broken, no matter what image I upload

如何解决这个问题?

mongodb reactjs express mongoose axios
1个回答
1
投票

避免发回base64编码图像(多个图像+大文件+大编码字符串=非常慢的性能)。我强烈建议创建一个只处理图像上传和任何其他图像相关的get / post / put / delete请求的微服务。将其与主应用程序分开。

例如:

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

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


例如,用户使用某些FormData向http://localhost:4000/api/avatar/create发送发布请求:

它首先通过一些Express中间件:

库/ middlewares.js

...
app.use(cors({credentials: true, origin: "http://localhost:3000" })) // allows receiving of cookies from front-end

app.use(morgan(`tiny`)); // logging framework

app.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.urlencoded({ limit: `10mb`, extended: true })); // allows objects and arrays to be URL-encoded

...etc     

然后,击中avatars路线:

路线/ avatars.js

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

然后它通过一些用户身份验证,然后通过我的saveImage中间件:

服务/ 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())

如果文件已保存,则会将req.file.path发送到我的create控制器。这将作为文件路径和图像路径保存到我的数据库中(为了删除目的保存avatarFilePath/uploads/imagefile.ext并保存avatarURL[http://localhost:4000]/uploads/imagefile.ext并用于前端GET请求):

controllers / avatars.js(我正在使用Postgres,但你可以替代Mongo)

create: async (req, res, done) => {
            try {
                const avatarurl = `${apiURL}/${req.file.path}`;

                await db.result("INSERT INTO avatars(userid, avatarURL, avatarFilePath) VALUES ($1, $2, $3)", [req.session.id, avatarurl, req.file.path]);

                res.status(201).json({ avatarurl });
            } catch (err) { return res.status(500).json({ err: err.toString() }); done(); 
        }

然后当前端尝试通过uploads<img src={avatarURL} alt="image" />访问<img src="[http://localhost:4000]/uploads/imagefile.ext" alt="image" />文件夹时,它会被微服务提供:

库/ server.js

const express = require("express");
const path = app.get("path");
const PORT = 4000;

//============================================================//
// EXPRESS SERVE AVATAR IMAGES
//============================================================//
app.use(`/uploads`, express.static(`uploads`));

//============================================================//
/* CREATE EXPRESS SERVER */
//============================================================//
app.listen(PORT);

记录请求时的外观:

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 ms

GET /uploads/1536891474536-k9c7OdimjEWYXbjTIs9J4S3lh2ldrzV8-android.png 200 3027 - 3.877 ms

用户在成功获取GET请求时看到的内容:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.