我正在尝试制作一个简单的输入按钮,用户可以单击该按钮将图像(.png)文件上传到Firebase-Storage (v.9)和React (用于未经身份验证的用户)。
以下是组件:
import { useState } from 'react';
import { storage } from './firebase.config';
import { ref, uploadBytes } from 'firebase/storage';
console.log(storage); // getting the storage object
export default function Upload() {
const [img, setImg] = useState(null);
const [imgError, setImgError] = useState(null);
// handle submit
const handleSubmit = async e => {
e.preventDefault();
const uploadPath = `images/${img.name}`; // geting the image path
const storageRef = ref(storage, uploadPath); // getting the storageRef
uploadBytes(storageRef, img)
.then(snapshot => console.log(snapshot))
.catch(err => console.log(err.message));
};
// handle upload
const handleUpload = e => {
setImgError(null);
let selected = e.target.files[0];
if (!selected) {
setImgError('Please select file');
return;
}
if (!selected.type.includes('image')) {
setImgError('Please select image file');
return;
}
if (selected.size > 1000000) {
setImgError('Please select smaller file size');
return;
}
setImgError(null);
setImg(selected);
};
return (
<div>
<h1>Upload component</h1>
<form onSubmit={handleSubmit}>
<label>
<span>Select image file</span>
<input type='file' onChange={handleUpload} required />
</label>
<button>Add to storage</button>
{setImgError && <p>{imgError}</p>}
</form>
</div>
);
}
下面是Firebase配置文件。
import { initializeApp } from 'firebase/app';
import { getStorage } from 'firebase/storage';
const firebaseConfig = {
apiKey: 'here is the key',
authDomain: 'here is the authDomain',
projectId: 'here is the project ID',
storageBucket: 'here is the storageBucket',
messagingSenderId: 'here is the messagingSenderId',
appId: 'here is appId',
};
// init App
const firebaseApp = initializeApp(firebaseConfig);
// init Storage
export const storage = getStorage(firebaseApp);
这是Firebase-Storage规则文件。
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
但是,它不起作用。我试着用谷歌搜索错误信息,但可以找到解决方案。
防火墙存储:发生了未知错误,请检查错误有效负载以获得服务器响应。(存储/未知)不良请求
我跟踪了这些文档:https://firebase.google.com/docs/storage/web/upload-files
发布于 2022-05-08 19:47:54
今天也有类似的事情。
我通过手动创建父文件夹来解决这个问题。在您的情况下,我建议您先创建images
文件夹,然后重新运行代码。
祝好运!
https://stackoverflow.com/questions/70041236
复制相似问题