我如何从我上传的文件中获取 link 到 firebase 以传递给 img 元素?
how do i get the link from my uploaded file to firebase to pass to img element?
我正在尝试上传图片,然后在页面上显示图片。我怎么做?我目前收到以下错误:Uncaught (in promise) TypeError: firebase__WEBPACK_IMPORTED_MODULE_2_.storage.ref is not a function
在 Observer.next.
此外,默认图像不会改变。我设法 console.log 图像 link,但我无法将其分配给变量。
图像已上传到 firebase 服务器。
import React, { useState, useEffect } from "react";
import { Paper } from "@mui/material";
import authHeader from "../../features/authentication/AuthHeader";
import { storage } from "./firebase";
import { getDownloadURL, uploadBytesResumable, ref } from "firebase/storage";
function UserProfile() {
const [user, setUser] = useState({});
const [Url, setUrl] = useState('');
async function fetchUser() {
const response = await fetch("http://localhost:9005/getProfile", {
headers: authHeader(),
});
const fetchedUser = await response.json();
console.log(fetchedUser);
setUser(fetchedUser);
}
useEffect(() => {
fetchUser();
}, []);
//firebase upload below this
const [progress, setProgress] = useState(0);
const handleFireBaseUpload = (e) => {
e.preventDefault();
const image = e.target[0].files[0];
console.log("uploading pic");
console.log(image);
uploadImage(image);
};
const uploadImage = (image) => {
if (!image) {
alert(`image format not supported${typeof image}`);
return;
}
const storageRef = ref(storage, `/images/${image.name}`);
const uploadTask = uploadBytesResumable(storageRef, image);
uploadTask.on( "state_changed", (snapshot) => {
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(prog);
storage.ref('images').child(image.name).getDownloadURL()
.then((url)=>{
setUrl(url);
});
},
(err) => console.log(err),
() => {
getDownloadURL(uploadTask.snapshot.ref).then((url) => console.log(url));
}
);
};
return (
<>
<paper elevation={6}>
<h3>Upload Progress ${progress} %</h3>
<div className="pfp">
<form onSubmit={handleFireBaseUpload}>
<input type="file" />
<p>hgk</p>
<button>Upload</button>
</form>
<img src={'https://th.bing.com/th/id/OIP.j3uYsrDvDgb3iLXvx1kcDgHaGh?pid=ImgDet&rs=1'} alt="Profile Picture" />
</div>
</paper>
<Paper
elevation={6}
style={{ margin: "10px", padding: "15px", textAlign: "left" }}
key={user.user_id}
>
First Name: {user.firstName}
<br />
Last Name: {user.lastName}
<br />
Email: {user.email}
<br />
Phone: {user.phone}
</Paper>
</>
);
}
export { UserProfile as default };
您应该在上传图片后更新 URL。 storage.ref('images')
也是 name-spaced 语法。新的 V9 SDK 有一个函数式语法,您可以使用它在下面下载 URL。尝试重构代码,如下所示:
uploadTask.on("state_changed", (snapshot) => {
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(prog);
// Don't fetch downloadURL here, just track progress
},
(err) => console.log(err),
() => {
// Get download URL here
getDownloadURL(uploadTask.snapshot.ref).then((url) => {
setUrl(url);
console.log(url)
})
}
);
我正在尝试上传图片,然后在页面上显示图片。我怎么做?我目前收到以下错误:Uncaught (in promise) TypeError: firebase__WEBPACK_IMPORTED_MODULE_2_.storage.ref is not a function 在 Observer.next.
此外,默认图像不会改变。我设法 console.log 图像 link,但我无法将其分配给变量。
图像已上传到 firebase 服务器。
import React, { useState, useEffect } from "react";
import { Paper } from "@mui/material";
import authHeader from "../../features/authentication/AuthHeader";
import { storage } from "./firebase";
import { getDownloadURL, uploadBytesResumable, ref } from "firebase/storage";
function UserProfile() {
const [user, setUser] = useState({});
const [Url, setUrl] = useState('');
async function fetchUser() {
const response = await fetch("http://localhost:9005/getProfile", {
headers: authHeader(),
});
const fetchedUser = await response.json();
console.log(fetchedUser);
setUser(fetchedUser);
}
useEffect(() => {
fetchUser();
}, []);
//firebase upload below this
const [progress, setProgress] = useState(0);
const handleFireBaseUpload = (e) => {
e.preventDefault();
const image = e.target[0].files[0];
console.log("uploading pic");
console.log(image);
uploadImage(image);
};
const uploadImage = (image) => {
if (!image) {
alert(`image format not supported${typeof image}`);
return;
}
const storageRef = ref(storage, `/images/${image.name}`);
const uploadTask = uploadBytesResumable(storageRef, image);
uploadTask.on( "state_changed", (snapshot) => {
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(prog);
storage.ref('images').child(image.name).getDownloadURL()
.then((url)=>{
setUrl(url);
});
},
(err) => console.log(err),
() => {
getDownloadURL(uploadTask.snapshot.ref).then((url) => console.log(url));
}
);
};
return (
<>
<paper elevation={6}>
<h3>Upload Progress ${progress} %</h3>
<div className="pfp">
<form onSubmit={handleFireBaseUpload}>
<input type="file" />
<p>hgk</p>
<button>Upload</button>
</form>
<img src={'https://th.bing.com/th/id/OIP.j3uYsrDvDgb3iLXvx1kcDgHaGh?pid=ImgDet&rs=1'} alt="Profile Picture" />
</div>
</paper>
<Paper
elevation={6}
style={{ margin: "10px", padding: "15px", textAlign: "left" }}
key={user.user_id}
>
First Name: {user.firstName}
<br />
Last Name: {user.lastName}
<br />
Email: {user.email}
<br />
Phone: {user.phone}
</Paper>
</>
);
}
export { UserProfile as default };
您应该在上传图片后更新 URL。 storage.ref('images')
也是 name-spaced 语法。新的 V9 SDK 有一个函数式语法,您可以使用它在下面下载 URL。尝试重构代码,如下所示:
uploadTask.on("state_changed", (snapshot) => {
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(prog);
// Don't fetch downloadURL here, just track progress
},
(err) => console.log(err),
() => {
// Get download URL here
getDownloadURL(uploadTask.snapshot.ref).then((url) => {
setUrl(url);
console.log(url)
})
}
);