我已经给出了多个上传文件选项,但它将所有内容存储在一个变量中,但我没有得到如何将单独的文件编码值存储在单独的变量中。它应该根据文件上传创建变量和存储编码值。
<html>
<body>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" multiple />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL(index) {
var filesSelected = document.getElementById("inputFileToLoad").files;
index = index || 0;
if (filesSelected.length > 0 && index < filesSelected.length) {
var fileToLoad = filesSelected[index];
var fileReader = new FileReader();
fileReader.onloadend = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").appendChild(newImage);
if (index < filesSelected.length) {
encodeImageFileAsURL(index + 1)
}
console.log(srcData);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
您可以将变量保存到数组中,然后随时访问它。
var sourceArray = new Array(); // put this before the function delaction
fileReader.onloadend = function (fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
sourceArray.push(srcData);
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").appendChild(newImage);
if (index < filesSelected.length) {
encodeImageFileAsURL(index + 1)
}}
console.log(sourceArray);