0
我的代碼正在將來自輸入的圖像存儲在本地存儲器中。我想使用類似window.location.href =「/ case-form」的方式更改我的頁面;當存儲所有圖像時(在完成onInputChange功能中的所有動作後)。在本地存儲器中存儲所有圖像後如何調用功能
$(document).ready(function() {
$(document).on('change', '#images-upload-input', function() {
onInputChange();
});
});
function onInputChange() {
clearStockedImages();
//get files from #images-upload-input input
var files = $("#images-upload-input", 'body')[0].files;
for (var i = 0; i < files.length; i++) {
if (files && files[i]) {
$('body').append("<img src='' id='photo-upload-" + i + "'/>");
var reader = new FileReader();
reader.onload = (function(i) {
return function(e) {
document.getElementById('photo-upload-' + i).src = e.target.result;
storeBase64Image(document.getElementById('photo-upload-' + i), function(result) {
localStorage.setItem('imgData-' + i, result);
});
};
})(i);
reader.readAsDataURL(files[i]);
}
}
}
//Delete all images previously stocked in local storage
function clearStockedImages() {
Object.keys(localStorage)
.forEach(function(key) {
if (/^(?:imgData-)/.test(key)) {
localStorage.removeItem(key);
}
});
}
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
function storeBase64Image(img, store) {
if (img.complete) {
store(getBase64Image(img));
} else {
img.onload = function() {
store(getBase64Image(img));
};
}
}
非常感謝。我早些時候嘗試過,但似乎我有另一個問題,讓我相信它沒有奏效。 –