javascript - 使用画布将文件输入到 blob
问题描述
无法将 blob 插入 indexedDB 请协助将 blob 从文件插入 indexedDB :)
代码
<html>
<head>
<title>file to BLOB</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="test">
<input id="File" type="file" accept="image/*" capture="user">
</div>
</body>
</html>
<script src="js/idbConn.js"></script>
Javascript
<script>
$(document).ready(function(){
$("#File").change(function(){
const File = this.files[0];
const cvs = document.createElement("canvas");
const optBlob = cvs.toBlob(function(cvsBlob){
let fileURL = URL.createObjectURL(File);
let imgFile = new Image();
let imgFile.src = fileURL;
imgFile.onload = function(){
cvs.width = imgFile.naturalWidth;
cvs.height = imgFile.naturalHeight;
let ctx = cvs.getContext("2d").drawImage(imgFile,0,0);
URL.revokeObjectURL(fileURL);
}
},File.type,0.3);
const data = new Object();
data.blob = optBlob;
let trx = db.transaction(["imgBlobs"],"readwrite").objectStore("imgBlobs").put(data,"test.jpeg");
});
});
</script>
试图直接将文件插入 indexedDB 但 blob 未定义
如果将 cvsBlob 保存在 data.blob 中,则空白图像存储在 indexedDB 中
解决方案
有几个问题。
HTMLCanvasElement.toBlob
不返回任何东西。您在回调函数中获得了 blob。- JavaScript 是阻塞的,排队的任务(如
toBlob
回调)事件(如onload
)在当前执行返回之前不会运行。这意味着该const data = new Object();
行在调用 toBlob 回调之前运行。 toBlob
您在创建、加载图像并将其绘制到画布之前调用。let imgFile.src = fileURL;
这一行会抛出语法错误??
使固定
- 首先加载图像。
- 在图像加载时创建画布并在其上绘制图像。
- 撤消图片网址。
- 将画布转换为 blob。
- 在
toBlob
回调中将 blob 添加到数据库。
例子
使用从文件输入中获得的文件调用该函数。例如 $("#File").change(function() { saveImageToDB(this.files[0]) });
function saveImageToDB(file) {
const fileURL = URL.createObjectURL(file);
const img = new Image();
img.src = fileURL;
img.addEventListener("load", () => {
URL.revokeObjectURL(fileURL);
const cvs = document.createElement("canvas");
cvs.width = img.naturalWidth;
cvs.height = img.naturalHeight;
cvs.getContext("2d").drawImage(img, 0, 0);
cvs.toBlob(blob => {
// Code to add blob to database. Put your db code in here
db.transaction(["img"], "write").objectStore("imgs").put({blob}, file.name);
}, File.type, 0.3);
}, {once: true});
}
推荐阅读
- azure-devops - Vsts VS build 找不到 .sln
- c# - 需要帮助在(十六进制)网格上修改我的 A*,该网格主要是“障碍物”,但演员可以跳过 X 块
- c# - 我如何知道我的 WAV 数据在 WAV 文件中从哪里开始,以便我可以读取它之前的 XML?
- java - 在 java Mockito 中模拟 httpclient v4
- python-3.x - 如何使 tkinter::pack() 将标签放在下面程序的左上角?
- css - CSS 内容属性中的 SVG 精灵
- javascript - React useState 无法更新双向绑定
- android - 如何禁用片段的过渡?
- python - 通过创建处理程序类避免重复代码
- haskell - 是否可以在 Haskell 中否定类型参数约束?