在react-native中如何从服务器渲染图像(使用node、express、multer和mongoDB)

idv4meu8  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(127)

I successfully store images from my react-native App into my /public folder in a server, using multer and storing the name and uri then into mongoDB. But I got stuck in trying to render the image back on my App.
How can I transform the server-image-url into a renderable image on the frontend?
This is the response I get from getProfileImage:

Object {
  "res": Object {
    "image": "public\\9180658ed9d83f98e4f20ed59906b0e49b74c2dd.jpeg",
    "name": "9180658ed9d83f98e4f20ed59906b0e49b74c2dd.jpeg",
    "status": "success",
  },
}

This is my backend for storing/retrieving images:

exports.uploadImage = async (req, res) => {
  const userId = req.body.userId
  const reqFiles = req.file

  try {
    const user = await User.findByIdAndUpdate(
      userId,
      {
        image: {
          public_id: nanoid(5),
          uri: reqFiles.path,
          name: reqFiles.filename,
        },
      },
      { new: true }
    )
    console.log('IMAGE ADDED TO DB-USER------> ', user)
    return res.json({
      _id: user._id,
      name: user.name,
      email: user.email,
      image: user.image,
    })
  } catch (error) {
    res.json({
      error,
    })
  }
}

exports.serveImage = async (req, res) => {
  const userId = req.body.userId
  try {
    const imageOnServer = await User.findById(userId)
    console.log({ imageOnServer })
    // res.sendFile(
    //   path.join(
    //     __dirname,
    //     '../public/4c1a69b2ec1cded57e9668af94c909fb68957387.jpeg'
    //   )
    // )
    res.status(200).json({
      status: 'success',
      image: imageOnServer.image.uri,
      name: imageOnServer.image.name,
    })
  } catch (error) {
    res.json({
      status: 'Failed to load image',
      error,
    })
  }
}

This is my multer configuration:

const multerStorage = multer.diskStorage({
 
  destination: (req, file, cb) => {
    cb(null, 'public')
  },
  filename: (req, file, cb) => {
    const name = file.originalname.split('.')

    let fName =
      crypto.randomBytes(20).toString('hex') + '.' + name[name.length - 1]

    cb(null, fName)
  },
})

const multerFilter = (req, file, cb) => {
  const restrictedExts = ['jfif']
  const ext = file.originalname.split('.').pop()

  if (restrictedExts.indexOf(ext) !== -1) {
    return cb(null, false)
  }

  switch (file.mimetype) {
    case 'image/jpeg':
      break
    case 'image/jpg':
      break
    case 'image/png':
      break
    default:
      cb(null, false)
      break
  }

  cb(null, true)
}

const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter,
})

Can anyone see what is missing? Thx!

yc0p9oo0

yc0p9oo01#

如果你有一个图片的网址(从你的问题我看到你有public\\9180658ed9d83f98e4f20ed59906b0e49b74c2dd.jpeg),我建议你使用https://github.com/DylanVann/react-native-fast-image组件。它有缓存设置,工作非常快。

import FastImage from 'react-native-fast-image'

const YourImage = () => (
    <FastImage
        style={{ width: 200, height: 200 }}
        source={{
            uri: res.image,
            priority: FastImage.priority.normal,
        }}
        resizeMode={FastImage.resizeMode.contain}
    />
)

相关问题