【问题标题】: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 上的示例。任何人都可以提出一些建议。
谢谢
【问题讨论】:
标签:
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.