IndexedDB는 Blob 저장을 지원하지만 Blob 인덱싱을 지원하지 않습니다. 인덱서 블 속성은 문자열, 숫자, 날짜 또는 배열 형식 일 수 있습니다. < 문자열 | 번호 | 날짜는 >입니다. 그렇지 않다면, IndexedDB는 자동으로 특정 객체를 색인하기 위해 무시할 것입니다.
또한 샘플 코드에서 artwork 테이블을 참조하지 않고 blob 속성이 포함 된 문서를 넣는 대신 blob을 단독으로 넣으려고합니다.
대신 할 수있는 것은 얼룩 콘텐츠의 해시/다이제스트를 계산하고 고유 색인을 사용하여 색인을 생성 할 수있는 문자열로 저장하는 것입니다.
var dbArt = new Dexie('TheDatabase');
dbArt.version(1).stores({
artworks: `
++id,
title,
album,
&artworkDigest` // & = unique index of the digest
});
var artworkBlob = getBlob(image); // get it somehow...
// Now, compute hash before trying to put blob into DB
computeHash(artworkBlob).then(artworkDigest => {
// Put the blob along with it's uniqely indexed digest
return dbArt.artworks.put({
title: theTitle,
album: theAlbum,
artwork: artworkBlob,
artworkDigest: artworkDigest
});
}).then(()=>{
console.log("Successfully stored the blob");
}).catch(error => {
// Second time you try to store the same blob, you'll
// end up here with a 'ConstraintError' since the digest
// will be same and conflict the uniqueness constraint.
console.error(`Failed to store the blob: ${error}`);
});
function computeHash (blob) {
return new Promise((resolve, reject) => {
// Convert to ArrayBuffer
var fileReader = new FileReader();
fileReader.onload =() => resolve(filerReader.result);
fileReader.onerror =() => reject(filerReader.error);
fileReader.readAsArrayBuffer(blob);
}).then (arrayBuffer => {
// Compute Digest
return crypto.subtle.digest("SHA-256", arrayBuffer);
}).then (digest => {
// Convert ArrayBuffer to string (to make it indexable)
return String.fromCharCode.apply(
null, new Uint8Array(digest));
});
};
나는 또한 나의 샘플이 표시되지 않습니다 우리는 어쨌든 ArrayBuffer에 방울을 읽을 수 있기 때문에 (오히려 BLOB보다 ArrayBuffer를 저장하는 것이 좋습니다,하지만 당신은 두 개의 서로 다른 기능으로 computeHash()을 분할 할 수 있습니다. - blob을 ArrayBuffer로 읽어 들이고, 다른 하나는 해쉬합니다 .Buffer 대신 ArrayBuffer를 저장하면 Safari 및 이전 버전의 firefox에서는 오류가 발생하지 않습니다.
사이드 노트 : IndexedDB 2.0에서 ArrayBuffers는 색인 가능합니다 (그러나 Blob은 아직 없습니다). 그러나 모든 데이터베이스에서 큰 값을 인덱싱하지 않는 것이 좋습니다. 다이제스트를 색인화하는 것이 더 좋습니다.
해시 코드 사용을 권합니다. – Josh
실제로 (* SparkMD5를 사용하여) 별도의 저장소에 아트웍을 저장하기위한 해싱 방법을 구현했지만 그럴 필요가 없다고 생각합니다. 'IndexedDB' 색인 및 고유 제한. Blob이 지원되지 않을 수도 있다고 생각하지 않았다. –
예, 코드 전송 오류였습니다. 결정된. –