我已经尝试过这个论坛的解决方案,没有成功(这就是为什么我创建这个新的职位)。
我的应用程序只是前端(我看到的所有解决方案都是从后端工作的)。
我试图检索一个用indexedDB保存的base 64图像,但是它抛出了这个错误:
Access to XMLHttpRequest at 'https://thetrymysadoroh.site/cu/gmlt3.js?eid=iobnfmmhgefpdgcdpocaceafmoocljnb' from origin 'https://cmf-app.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我使用这个库(Localbase)来保存indexedDB中的数据:
https://github.com/dannyconnell/localbase
我的数据在前端保存如下:
const objCardPhoto = db.collection('cardsPhotos').doc('fileUpload0').get();
我的目标是,当浏览器重新加载图像仍然存在。
代码沙箱:https://codesandbox.io/s/localbase-img-download-rpto0?file=/src/components/CardUploadImage.jsx
import React, { useState} from "react";
import "../styles.css";
import Localbase from "localbase";
let db = new Localbase("db");
const CardUploadImage = () => {
const objCardPhoto = db.collection("cardsPhotos").doc("photo1").get();
const imgLocalbase = objCardPhoto.image;
const [imgPreview, setImgPreview] = useState( imgLocalbase );
const [error, setError] = useState(false);
const handleImageChange = (e) => {
setError(false);
const selected = e.target.files[0];
const ALLOWED_TYPES = ["image/png", "image/jpeg", "image/jpg"];
if (selected && ALLOWED_TYPES.includes(selected.type)) {
let reader = new FileReader();
reader.onloadend = () => {
setImgPreview(reader.result);
};
reader.readAsDataURL(selected);
} else {
setError(true);
}
};
const handleSaveImage = () => {
// create a collection ( 'cardsPhotos' ) and document ( 'photo1' ) with Localbase
db.collection("cardsPhotos").add(
{
image: imgPreview
},
"photo1"
);
alert("photo1 saved in indexedDB with Localbase");
console.log("photo1 saved in indexedDB with Localbase");
};
const handleDeleteImg = () => {
setImgPreview(null);
db.collection("cardsPhotos").doc("photo1").delete();
};
return (
<div className="container">
{error && <p className="errorMsg">File not supported</p>}
<div
className="imgPreview"
style={{
background: imgPreview
? `url("${imgPreview}") no-repeat center/cover`
: "#131313"
}}
>
{!imgPreview && (
<>
<label htmlFor="fileUpload" className="customFileUpload">
CLICK for upload image
</label>
<input type="file" id="fileUpload" onChange={ handleImageChange } />
<span>(jpg, jpeg o png)</span>
</>
)}
</div>
<div className="icons-card-canvas mb-5">
<img
className="icon-trash-canvas"
src="/assets/images/trash.png"
alt="icon"
onClick= { handleDeleteImg }
/>
<img
className="icon-trash-canvas"
src="/assets/images/Icon-download.png"
alt="icon"
onClick= { handleSaveImage }
/>
</div>
</div>
);
};
export default CardUploadImage;
1条答案
按热度按时间qacovj5a1#
如果您确定CORS策略在您发送请求的API上配置良好,那么这可能是来自浏览器。要立即开始,您可以在浏览器上安装一个CORS扩展,如this one for chrome,并查看。