Javascript - 文件上传,readAsArrayBuffer?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26946548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - File uploading, readAsArrayBuffer?
提问by Cheese Puffs
i'm currently trying to upload a file to my server. But i'm not really sure how to do this with readAsArrayBuffer. This works if I use readAsBinaryString.
我目前正在尝试将文件上传到我的服务器。但我不太确定如何使用readAsArrayBuffer做到这一点。如果我使用readAsBinaryString ,这会起作用。
If i try to console.log it only returns 'arrayBuffer: {}'.After I've tried to upload it, i can see inside post that only a empty object was sent. If I use readAsBinaryString, I see a bunch of binary code.
如果我尝试 console.log 它只返回“arrayBuffer:{}”。在我尝试上传后,我可以看到内部帖子只发送了一个空对象。如果我使用 readAsBinaryString,我会看到一堆二进制代码。
var file = document.getElementById('my_file').files[0],
reader = new FileReader();
reader.onloadend = function(e){
console.log(e.target.result);
$scope.image = e.target.result;
}
reader.readAsArrayBuffer(file);
How can I see my file, so I know it's working when using readAsArrayBuffer? If more code is needed let me know! Thanks.
我怎样才能看到我的文件,所以我知道它在使用 readAsArrayBuffer 时正在工作?如果需要更多代码,请告诉我!谢谢。
采纳答案by Ajeet Lakhani
If you want to upload am image then you have to convert it into base64 format. You can do it either by using canvas element or by using Filereader.If you are using Filereader then you have to use readAsDataURL()
如果要上传图片,则必须将其转换为 base64 格式。您可以通过使用 canvas 元素或使用 Filereader 来做到这一点。如果您使用的是 Filereader,那么您必须使用readAsDataURL()
You can refer MDN for this https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL
您可以为此https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL参考 MDN
also you can use canvas element Convert an image to canvas that is already loaded
您也可以使用 canvas 元素 将图像转换为已经加载的画布
回答by dreyescat
According to ArrayBufferdocumentation
根据ArrayBuffer文档
You can not directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
您不能直接操作 ArrayBuffer 的内容;相反,您创建一个类型化数组对象或一个以特定格式表示缓冲区的 DataView 对象,并使用它来读取和写入缓冲区的内容。
So as I commented before probably console.log
doesn't know how to represent the buffer and therefore it simply outputs arrayBuffer: {}
.
因此,正如我之前评论的那样,可能console.log
不知道如何表示缓冲区,因此它只是输出arrayBuffer: {}
.
If you want to show something in the console you need to use a typed array or a DataView. For example using an Int8Array
:
如果要在控制台中显示某些内容,则需要使用类型化数组或 DataView。例如使用Int8Array
:
reader.onloadend = function (e) {
console.log(e);
console.log(new Int8Array(e.target.result));
};
See demo
看演示