前端JS中使用XMLHttpRequest 2上传图片到服务器,PC端和大部分手机上都正常,但在少部分安卓手机上上传失败,服务器上查看图片,显示字节数为0。下面是上传图片的核心代码:
HTML
<input type="file" id="choose" capture="camera" accept="image/*">
JavaScript
var filechooser = document.getElementById("choose"); filechooser.onchange = function () { var _this = $(this); if (!this.files.length) return; var files = Array.prototype.slice.call(this.files); if (files.length > 1) { alert("一次只能上传1张图片"); return; } files.forEach(function (file, i) { if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return; var reader = new FileReader(); reader.onload = function () { var result = this.result; upload(result, file.type); }; reader.readAsDataURL(file); }); }; function upload(basestr, type){ var xhr = new XMLHttpRequest(); var text = window.atob(basestr.split(",")[1]); var buffer = new Uint8Array(text.length); var pecent = 0; for (var i = 0; i < text.length; i++) { buffer[i] = text.charCodeAt(i); } var blob = getBlob(buffer, type); var formdata = new FormData(); formdata.append('imagefile', blob); xhr.open('post', '/uploadtest'); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var jsonData = JSON.parse(xhr.responseText); console.log(jsonData); } }; //利用progress事件显示数据发送进度 xhr.upload.addEventListener('progress', function (e) { pecent = ~~(100 * e.loaded / e.total) / 2; // 利用pecent来显示上传进度 }, false); xhr.send(formdata); } function getBlob(buffer, format){ var Builder = window.WebKitBlobBuilder || window.MozBlobBuilder; if(Builder){ var builder = new Builder(); builder.append(buffer); return builder.getBlob(format); } else { return new window.Blob([ buffer ], {type: format}); } }
上述代码使用FormData来实现表单数据提交。FormData是一种针对XHR2设计的新型数据类型,使用它我们可以很方便地实时以JavaScript创建HTML