【问题标题】:how to upload image in the firebase storage and get uploaded image url in react using swr-firestore如何在firebase存储中上传图片并使用swr-firestore在react中获取上传的图片url
【发布时间】:2021-08-20 07:06:15
【问题描述】:

我正在使用 firebase 通过 swr-firestore 存储数据。到目前为止还不错。现在我需要将图像上传到 Firebase 存储。我怎么能用 swr-firestore 的 fuego 做到这一点。任何建议。 https://github.com/nandorojo/swr-firestore.

使用 fuego 我在 firebase 中调用节点函数,使用 useCollection 我从所需的集合中获取数据。我也可以更新与收藏相关的记录数据。但我没有找到任何将 imate 存储在 firestore 上的示例。任何人都可以提出一些建议。 谢谢

【问题讨论】:

  • 一种经典的方法是将图像存储在Cloud Storage 中,然后获取您存储在 Firestore 中的签名 URL。

标签: reactjs firebase google-cloud-firestore


【解决方案1】:

在 nextJs 中,将图片上传到 firebase 是在长时间搜索之后完成的。

app.tsx
=======

import 'firebase/firestore'
import 'firebase/auth'
import 'firebase/functions'
import 'firebase/storage'
import { FuegoProvider } from '@nandorojo/swr-firestore'
import { Fuego } from '@/utilities/fuego'

const fc = {
apiKey: API_KEY,
authDomain: AUTH_DOMAIN,
projectId: PROJECT_ID,
storageBucket: STORAGE_BUCKET,
messagingSenderId: MESSAGE_SENDER_ID,
appId: APP_ID,
measurementId: MEASUREMENT_ID,
}

const fGo = new Fuego(fc)

const MyApp: React.FC<AppProps> = ({ Component, pageProps }) => {
return (
<FuegoProvider fGo={fGo}>
  <Component {...pageProps} />
</FuegoProvider>
)
}

xyz.tsx:
=======
import { fGo } from '@nandorojo/swr-firestore'
const [imageAsFile, setImageAsFile] = useState('' as any)
const onSubmit = async (data: any) => {
if (imageAsFile === '') {
  console.error(`not an image, the image file is a ${typeof 
 imageAsFile}`)
 }
 const fileNewName = new Date().getTime() + imageAsFile.name
 let finalUrl = ''
 const uploadTask = 
fGo.storage().ref(`/mypics/${fileNewName}`).put(imageAsFile)
 await uploadTask.on(
  'state_changed',
  (snapShot: any) => {
    console.log(snapShot)
  },
  (err: any) => {
    console.log(err)
  },
  () => {
    fuego
      .storage()
      .ref('/mypics/')
      .child(fileNewName)
      .getDownloadURL()
      .then((fireBaseUrl: any) => {
        if (fireBaseUrl) {
          finalUrl = fireBaseUrl
        }
      })
  }
 )
 }


 return (
    <form onSubmit={handleSubmit(onSubmit)} autoComplete="off">
            <input
              type="file"
              name="profilePic"
              id="profilePic"
              onChange={(e) => {
                setImageAsFile(e?.target?.files?.[0])
              }}
            />
            <input type='submit' />
    </form>
)

Hi, finally i got how to upload and get back image url. "Renaud Tarnec" 
Tq.

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2021-06-28
    • 1970-01-01
    • 2017-12-12
    • 2020-04-18
    • 2020-10-05
    • 2017-09-19
    • 2017-03-03
    • 2018-11-13
    相关资源
    最近更新 更多