Firebase 9自定义缩略图DOC DOC上传和Avatar的缩略图负载

发布于 2025-02-03 05:54:53 字数 2879 浏览 3 评论 0原文

我试图重写4行Firebase V8代码与V9一起工作。 Shaun Pelling(Net Ninja's)Udemy Firebase/React课程的作品。

该代码实现了一个非常简单的目的:

我想将注释上传到firebase中的自定义文件路径中,以先前定义为filepath中的变量。然后上传文件。在我的nabber中,我还从第三行代码创建的URL显示了一个图像。

编辑:首先,这是文件最初从以下内容上传到的JSX:

<label>
  <span>Upload Profile Thumbnail:</span>
  <input
   required
   type="file"
   id="thumbnail"
   name="thumbnail"
  />
</label>

我指的是(V8)的原始4行:

  const res = await projectAuth.createUserWithEmailAndPassword(email, password)
        
  const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
  const image = await projectStorage.ref(uploadPath).put(thumbnail)
  const imageUrl = await image.ref.getDownloadURL()

  await res.user.updateProfile({ photoURL: imageUrl })

这是我所拥有的。 (这是一团乱)/)

  import { ref, getDownloadURL, uploadBytesResumable } from 'firebase/storage'
  import { updateProfile } from 'firebase/auth'
  
  const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
  const imageUrl = getDownloadURL(ref(storage, image))
  const uploadTask = uploadBytesResumable(storageRef, file, metadata )

  updateProfile(user, { photoURL: imageUrl})

sidenote: 哦,1可能不那么重要的旁注(而且很可能是不必要的),在V8示例中,缩略图在注册表单中上传,因此在第一个代码中的注册函数。在第二个示例V9中,我创建了一个全新的页面(仅用于用户签名),以便他们以后可以上传缩略图。为了这样做,我正在从当前签名的用户中拾取“用户”对象,以便使用UpdateProfile函数。 IE:

  // within the v9 code example
  const { user } = useAuthContext()


  //=======================================
  // in the useAuthContext File:

  import { AuthContext } from "../CONTEXT/AuthContext.js"
  import { useContext } from "react"

  export const useAuthContext = () => {
   const context = useContext(AuthContext)
   return context
  }


  //=======================================
  // in the authContext File:

  import { createContext, useReducer, useEffect } from 'react'
  import { onAuthStateChanged } from 'firebase/auth'
  import { auth } from '../Firebase/config'

  export const AuthContext = createContext()

  export const authReducer = (state, action) => {
   switch (action.type) {
   case 'LOGIN':
    return { ...state, user: action.payload }
   case 'LOGOUT':
    return { ...state, user: null }
   case 'AUTH_IS_READY':
    return { user: action.payload, authIsReady: true }
   default:
  return state
 }
}

export const AuthContextProvider = ({ children }) => {
 const [state, dispatch] = useReducer(authReducer, { 
  user: null,
  authIsReady: false
})

useEffect(() => {
 const unsub = onAuthStateChanged(auth, user => {
  dispatch({ type: 'AUTH_IS_READY', payload: user })
  unsub()
 })
}, [])

// console.log('AuthContext state:', state)

return (
 <AuthContext.Provider value={{ ...state, dispatch }}>
  { children }
 </AuthContext.Provider>
)

}

Im trying to rewrite 4 lines of firebase v8 code to work with v9.... but I'm stuck on these 3 lines, even after studying Firebase documentation.... This code is found within a form submit function and taken from one of Shaun Pelling's (the Net Ninja's) Udemy Firebase/React Course.

The code serves a pretty simple purpose:

I'd like to upload the comment to a custom file path within firebase taking in the userId (uid) previously defined as a variable in the filepath. Then upload the file. In my nabber I also have an image being displayed from the url created by the 3rd line of code.

EDIT: First, here's the JSX to which the file originally is uploaded from:

<label>
  <span>Upload Profile Thumbnail:</span>
  <input
   required
   type="file"
   id="thumbnail"
   name="thumbnail"
  />
</label>

the original 4 lines I'm referring to (v8):

  const res = await projectAuth.createUserWithEmailAndPassword(email, password)
        
  const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
  const image = await projectStorage.ref(uploadPath).put(thumbnail)
  const imageUrl = await image.ref.getDownloadURL()

  await res.user.updateProfile({ photoURL: imageUrl })

This is kind of what I've got. (It's a mess I don't don't think it even makes much sense. I'm a bit lost, so if it confuses you as well, please disregard... I just wanted to show I'm trying \(˚☐˚”)/)

  import { ref, getDownloadURL, uploadBytesResumable } from 'firebase/storage'
  import { updateProfile } from 'firebase/auth'
  
  const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
  const imageUrl = getDownloadURL(ref(storage, image))
  const uploadTask = uploadBytesResumable(storageRef, file, metadata )

  updateProfile(user, { photoURL: imageUrl})

SIDENOTE:
Oh, 1 little probably much less important sidenote (and more than likely unnecessary), In the v8 example, the thumbnail is uploaded within the signup form, hence the signup function in the first bit of code. In the second example v9, I created a whole new page (only available to signed in users) so that they can upload a thumbnail at a later time. In order to do so, I'm picking up the "user" object from the currentlysignedin user to be able to for instance use the updateProfile function. ie:

  // within the v9 code example
  const { user } = useAuthContext()


  //=======================================
  // in the useAuthContext File:

  import { AuthContext } from "../CONTEXT/AuthContext.js"
  import { useContext } from "react"

  export const useAuthContext = () => {
   const context = useContext(AuthContext)
   return context
  }


  //=======================================
  // in the authContext File:

  import { createContext, useReducer, useEffect } from 'react'
  import { onAuthStateChanged } from 'firebase/auth'
  import { auth } from '../Firebase/config'

  export const AuthContext = createContext()

  export const authReducer = (state, action) => {
   switch (action.type) {
   case 'LOGIN':
    return { ...state, user: action.payload }
   case 'LOGOUT':
    return { ...state, user: null }
   case 'AUTH_IS_READY':
    return { user: action.payload, authIsReady: true }
   default:
  return state
 }
}

export const AuthContextProvider = ({ children }) => {
 const [state, dispatch] = useReducer(authReducer, { 
  user: null,
  authIsReady: false
})

useEffect(() => {
 const unsub = onAuthStateChanged(auth, user => {
  dispatch({ type: 'AUTH_IS_READY', payload: user })
  unsub()
 })
}, [])

// console.log('AuthContext state:', state)

return (
 <AuthContext.Provider value={{ ...state, dispatch }}>
  { children }
 </AuthContext.Provider>
)

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羁绊已千年 2025-02-10 05:54:53

在V9代码片段中,您尝试在首先上传图像之前尝试获取下载URL。另外,如果您不需要跟踪更新进度,请使用uploadbytes()

import { ref, getDownloadURL, uploadBytesResumable } from 'firebase/storage'
import { updateProfile } from 'firebase/auth'

// pass the path in ref to create a StorageReference
const storageRef = ref(storage, `thumbnails/${res.user.uid}/${thumbnail.name}`)

// upload image, file is a blob here
await uploadBytes(storageRef, file);

const downloadUrl = await getDownloadURL(storageRef);

// this function returns promise too, add await 
await updateProfile(user, { photoURL: downloadUrl })

In the V9 code snippet, you are trying to get the download URL before even uploading the image at first place. Also if you don't need to track update progress, use uploadBytes() instead:

import { ref, getDownloadURL, uploadBytesResumable } from 'firebase/storage'
import { updateProfile } from 'firebase/auth'

// pass the path in ref to create a StorageReference
const storageRef = ref(storage, `thumbnails/${res.user.uid}/${thumbnail.name}`)

// upload image, file is a blob here
await uploadBytes(storageRef, file);

const downloadUrl = await getDownloadURL(storageRef);

// this function returns promise too, add await 
await updateProfile(user, { photoURL: downloadUrl })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文