React项目中Blob格式随机头像无法正常显示问题求助
问题:React项目中Google Drive图片转Blob后无法正常展示
我正在开发一个包含登录与注册功能的React项目,注册页面表单包含姓名、邮箱、头像URL、密码和确认密码输入项。其中头像URL为非必填字段,当用户未填写时,我希望从图片URL数组中随机选取并展示图片。所有图片均上传至Google Drive文件夹中,将每张图片转换为Blob格式后,浏览器能识别该Blob,但无法向用户正常展示。尝试过base64格式也存在同样问题。
后端图片接口代码
import fetch from "node-fetch"; import profileimages from "../profileImages.js"; export const images = async (req, res) => { try { // Randomly select an image URL const randomIndex = Math.floor(Math.random() * profileimages.length); const randomImageUrl = profileimages[randomIndex]; // Fetch the random image const response = await fetch(randomImageUrl); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } // Ensure the Content-Type header is set correctly const contentType = response.headers.get('content-type'); if (!contentType) { throw new Error('Content-Type header is missing in the response'); } // Fetch the image as an ArrayBuffer const arrayBuffer = await response.arrayBuffer(); // Create a Buffer from the ArrayBuffer const imageBuffer = Buffer.from(arrayBuffer); // Set the Content-Type header in the response res.setHeader('Content-Type', contentType); // Send the image buffer in the response res.send(imageBuffer); } catch (error) { console.error('Error fetching image:', error); res.status(500).send('Internal Server Error'); } };
前端获取头像与注册逻辑
export const getUserProfileImage = async () => { try { const response = await fetch('http://localhost:5500/images/user'); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const blob = await response.blob(); const imageUrl = URL.createObjectURL(blob); return imageUrl; } catch (err) { console.error('Error getting user profile image:', err); throw err; } }; export const register = async(data) =>{ const body = { name: data.name, email: data.email, userImage: data.userImage || await getUserProfileImage(), password: data.password, rPassword: data.rPassword, } if(body.password !== body.rPassword){ alert("Passwords need to match!"); throw new Error("Passwords need to match!"); } console.log(body) let response = await fetch(baseUrlRegister, { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) const result = await response.json(); console.log(result) if(result.status != 200){ alert(result.message) throw new Error(result.message); } localStorage.setItem("accessToken", result.accessToken); localStorage.setItem("auth", [result.data.name, result.data.email, result.data._id]) return result; }
注册页面组件代码
export function RegisterPage(){ //const accessToken = localStorage.getItem("accessToken") const [imageUrl, setImageUrl] = useState(''); useEffect(() => { const loadImage = async () => { try { const blob = await userService.getUserProfileImage(); setImageUrl(blob); } catch (error) { console.error('Error loading image:', error); } }; loadImage(); }, []); let navigate = useNavigate() async function register(e){ e.preventDefault(); if(document.getElementById("userImage").value == ""){ document.getElementById("userImage").value = imageUrl; } // Get data from form data const data = Object.fromEntries(new FormData(e.target.form)); console.log(data) // Create new user at the server await userService.register(data); document.getElementById("fullName").value = ""; document.getElementById("email").value = ""; document.getElementById("userImage").value = ""; document.getElementById("pass").value = ""; document.getElementById("rPass").value = ""; navigate("/") }
用户头像展示代码
useEffect(() => { userService.getOne(userId) .then(result => setUserImage(result.userImage)) }) <p> Profile Image: {<img src={userImage} alt="profileImage"></img>}{' '} </p>
内容的提问来源于stack exchange,提问作者sonyagenova
相关产品推荐
相关产品推荐

