gpt4 book ai didi

javascript - readAsDataURL 不返回图像类型

转载 作者:行者123 更新时间:2023-11-28 00:46:32 24 4
gpt4 key购买 nike

在使用 readAsDataURL 读取图像时,如何强制返回图像类型(如果没有返回),

window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
$("#file").on("change", function(event) {
event.preventDefault();
var output = document.getElementById("result");
existingNode = document.getElementById("addMore");
var files = event.target.files;
for (var i = 0; i < files.length; i++)
{
var file = files[i];
var picReader = new FileReader();
picReader.onload = function(event) {
var picFile = event.target;
var formElement = document.getElementById("submitForm");
var dataToBeSent = new FormData(formElement);

count++;
var div = document.createElement("div");
div.innerHTML = '<div class="fl pu_mr1 pu_mr2 wrap' + count + '">' + '<div class="photobox posrel">' + '<div class="posabs txtc fontlig color2 f14 lh30 pum35 dispnone retryMessage"><i class="up_sprite pu_retry pu_mt2"></i>Retry</div>' + "<img class='classimg1 opa50 uploading" + count + "' src='" + picFile.result + "'" + "title='" + picFile.name + "'/>" + '<div class="posabs pu_pos1" onclick="deleteThisPhoto(' + count + ')"><a href="#" class="up_sprite pu_cross"></a></div>' + '<div class="posabs fullwid pu_pos2 uploadingBar' + count + '">' + '<div class="wid80p brdr12">' + '<div class="bg7 hgt10 mrl0 uploadingPercent' + count + '" style="width:0px;"></div>' + '</div></div></div></div>';
output.insertBefore(div, existingNode);
generatingDiv.innerHTML = "";
formDataArray[count] = dataToBeSent;

};
picReader.readAsDataURL(file); //Read the image
}

最佳答案

File 对象具有包含 mime 类型的 type 属性:

for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileType = file.type;
console.log(fileType); // image/png
}

FileReader 对象返回一个同样具有 mime 类型的 base64 字符串,您可以使用此函数提取该字符串:

function base64MimeType(encoded) {
if (!encoded) return;
var mime = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);

if (mime && mime.length) return mime[1];
}

var picReader = new FileReader();
picReader.readAsDataURL(file);
var base64 = picReader.result;
console.log(base64MimeType(base54)); // image/png

JSFiddle 演示:http://jsfiddle.net/mr2g5dx1/2/

这是我创建的一个小模块:https://github.com/miguelmota/base64mime

关于javascript - readAsDataURL 不返回图像类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27309668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com