gpt4 book ai didi

javascript - Android Native 浏览器中上传的空文件

转载 作者:可可西里 更新时间:2023-11-01 18:47:30 26 4
gpt4 key购买 nike

我正在为手机创建一个可以调整照片大小并上传照片的网站。

$('#ImgPreview canvas').each(function(pIndex) {
vFormData.append(pIndex, canvasToJpegBlob($(this)[0]), vIssueId +'-attachment0'+ pIndex +'.jpg');
});

$.ajax({
url: '/api/ob/issuefileupload',
data: vFormData,
processData: false,
contentType: false,
type: 'POST'
}).done(function(pData) {
window.location = '/issue?id='+ vIssueId;
}).fail(function(pJqXHR) {
alert(My.Strings.UploadFailed);
});

这适用于 Android 版 Chrome 和 iOS 版 Safari,但在原生 Android 浏览器中,文件的内容长度为 0,名称为 Blob + 一个 UID。当文件被添加到表单数据时,大小似乎也相当大(900k 而不是 Chrome 中的 50k)。

canvasToJpegBlob 函数:

function canvasToJpegBlob(pCanvas) {
var vMimeType = "image/jpeg",
vDataURI,
vByteString,
vBlob,
vArrayBuffer,
vUint8Array, i,
vBlobBuilder;

vDataURI = pCanvas.toDataURL(vMimeType, 0.8);
vByteString = atob(vDataURI.split(',')[1]);

vArrayBuffer = new ArrayBuffer(vByteString.length);
vUint8Array = new Uint8Array(vArrayBuffer);
for (i = 0; i < vByteString.length; i++) {
vUint8Array[i] = vByteString.charCodeAt(i);
}

try {
vBlob = new Blob([vUint8Array.buffer], {type : vMimeType});
} catch(e) {
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;

if (e.name === 'TypeError' && window.BlobBuilder) {
vBlobBuilder = new BlobBuilder();
vBlobBuilder.append(vUint8Array.buffer);
vBlob = vBlobBuilder.getBlob(vMimeType);
} else if (e.name === 'InvalidStateError') {
vBlob = new Blob([vUint8Array.buffer], {type : vMimeType});
} else {
alert(My.Strings.UnsupportedFile);
}
}

return vBlob;
}

有什么方法可以让它在原生 Android 浏览器中运行吗?

最佳答案

我也遇到了这个问题,需要想出一个更通用的解决方案,因为在某些情况下我无法控制服务器端代码。

最终我找到了一个几乎完全透明的解决方案。该方法是用一个 blob 填充损坏的 FormData,该 blob 以 multipart/form-data 的必要格式附加数据。它使用将 blob 读入缓冲区的版本覆盖 XHR 的 send(),该缓冲区在请求中发送。

主要代码如下:

var
// Android native browser uploads blobs as 0 bytes, so we need a test for that
needsFormDataShim = (function () {
var bCheck = ~navigator.userAgent.indexOf('Android')
&& ~navigator.vendor.indexOf('Google')
&& !~navigator.userAgent.indexOf('Chrome');

return bCheck && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
})(),

// Test for constructing of blobs using new Blob()
blobConstruct = !!(function () {
try { return new Blob(); } catch (e) {}
})(),

// Fallback to BlobBuilder (deprecated)
XBlob = blobConstruct ? window.Blob : function (parts, opts) {
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
parts.forEach(function (p) {
bb.append(p);
});

return bb.getBlob(opts ? opts.type : undefined);
};

function FormDataShim () {
var
// Store a reference to this
o = this,

// Data to be sent
parts = [],

// Boundary parameter for separating the multipart values
boundary = Array(21).join('-') + (+new Date() * (1e16*Math.random())).toString(36),

// Store the current XHR send method so we can safely override it
oldSend = XMLHttpRequest.prototype.send;

this.append = function (name, value, filename) {
parts.push('--' + boundary + '\nContent-Disposition: form-data; name="' + name + '"');

if (value instanceof Blob) {
parts.push('; filename="'+ (filename || 'blob') +'"\nContent-Type: ' + value.type + '\n\n');
parts.push(value);
}
else {
parts.push('\n\n' + value);
}
parts.push('\n');
};

// Override XHR send()
XMLHttpRequest.prototype.send = function (val) {
var fr,
data,
oXHR = this;

if (val === o) {
// Append the final boundary string
parts.push('--' + boundary + '--');

// Create the blob
data = new XBlob(parts);

// Set up and read the blob into an array to be sent
fr = new FileReader();
fr.onload = function () { oldSend.call(oXHR, fr.result); };
fr.onerror = function (err) { throw err; };
fr.readAsArrayBuffer(data);

// Set the multipart content type and boudary
this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
XMLHttpRequest.prototype.send = oldSend;
}
else {
oldSend.call(this, val);
}
};
}

然后像这样使用它,然后像往常一样调用 fd.append(name, value):

var fd = needsFormDataShim ? new FormDataShim() : new FormData();

关于javascript - Android Native 浏览器中上传的空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15639070/

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