Javascript 从输入表单获取 Base64 编码文件数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6978156/
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
Get Base64 encode file-data from Input Form
提问by jordan.baucke
I've got a basic HTML form from which I can grab a bit of information that I'm examining in Firebug.
我有一个基本的 HTML 表单,我可以从中获取一些我正在 Firebug 中检查的信息。
My only issues is that I'm trying to base64encode the file data before it's sent to the server where it's required to be in that form to be saved to the database.
我唯一的问题是我试图在将文件数据发送到服务器之前对其进行base64编码,服务器需要以该形式保存到数据库中。
<input type="file" id="fileupload" />
And in Javascript+jQuery:
在 Javascript+jQuery 中:
var file = $('#fileupload').attr("files")[0];
I have some operations based on avaliable javascript: .getAsBinary(), .getAsText(), .getAsTextURL
我有一些基于可用 javascript 的操作:.getAsBinary(), .getAsText(), .getAsTextURL
However none of these return usable text that can be inserted as they contain unusable 'characters'- I don't want to have a 'postback' occur in my file uploaded, and I need to have multiple forms targeting specific objects so it's important I get the file and use Javascript this way.
然而,这些都没有返回可以插入的可用文本,因为它们包含不可用的“字符”——我不想在我上传的文件中出现“回发”,我需要有多个针对特定对象的表单,所以我很重要获取文件并以这种方式使用Javascript。
How should I get the file in such a way that I can use one of the Javascript base64 encoders that are widely avaliable!?
我应该如何以可以使用广泛可用的 Javascript base64 编码器之一的方式获取文件!?
Thanks
谢谢
Update - Starting bounty here, need cross browser support!!!
更新 - 从这里开始赏金,需要跨浏览器支持!!!
Here is where I'm at:
这是我所在的位置:
<input type="file" id="fileuploadform" />
<script type="text/javascript>
var uploadformid = 'fileuploadform';
var uploadform = document.getElementById(uploadformid);
/* method to fetch and encode specific file here based on different browsers */
</script>
Couple of issues with cross browser support:
跨浏览器支持的几个问题:
var file = $j(fileUpload.toString()).attr('files')[0];
fileBody = file.getAsDataURL(); // only works in Firefox
Also, IE doesn't support:
此外,IE 不支持:
var file = $j(fileUpload.toString()).attr('files')[0];
So I have to replace with:
所以我必须替换为:
var element = 'id';
var element = document.getElementById(id);
For IE Support.
对于 IE 支持。
This works in Firefox, Chrome, Safari (but doesn't properly encode the file, or at least after it's been posted the file doesn't come out right)
这适用于 Firefox、Chrome、Safari(但没有正确编码文件,或者至少在发布后文件没有正确显示)
var file = $j(fileUpload.toString()).attr('files')[0];
var encoded = Btoa(file);
Also,
还,
file.readAsArrayBuffer()
Seems to be only supported in HTML5?
好像只支持 HTML5?
Lots of people suggested:http://www.webtoolkit.info/javascript-base64.html
很多人建议:http ://www.webtoolkit.info/javascript-base64.html
But this only returns en error on the UTF_8 method before it base64 encodes? (or an empty string)
但这只会在 base64 编码之前在 UTF_8 方法上返回错误?(或空字符串)
var encoded = Base64.encode(file);
回答by beatgammit
It's entirely possible in browser-side javascript.
这在浏览器端 javascript 中是完全可能的。
The easy way:
简单的方法:
The readAsDataURL()method might already encode it as base64 for you. You'll probably need to strip out the beginning stuff (up to the first ,), but that's no biggie. This would take all the fun out though.
该readAsDataURL()方法可能已经对其进行编码为base64为您服务。您可能需要去掉开头的内容(直到第一个 ,),但这没什么大不了的。不过,这会带走所有的乐趣。
The hard way:
艰难的方式:
If you want to try it the hard way (or it doesn't work), look at readAsArrayBuffer()
. This will give you a Uint8Array and you can use the method specified. This is probably only useful if you want to mess with the data itself, such as manipulating image data or doing other voodoo magic before you upload.
如果您想以艰难的方式尝试(或不起作用),请查看readAsArrayBuffer()
. 这将为您提供一个 Uint8Array,您可以使用指定的方法。这可能仅在您想弄乱数据本身时才有用,例如在上传之前处理图像数据或执行其他巫术魔法。
There are two methods:
有两种方法:
- Convert to string and use the built-in
btoa
or similar- I haven't tested all cases, but works for me- just get the char-codes
- Convert directly from a Uint8Array to base64
- 转换为字符串并使用内置的
btoa
或类似的- 我没有测试过所有情况,但对我有用 - 只需获取字符代码
- 直接从 Uint8Array 转换为 base64
I recently implemented tar in the browser. As part of that process, I made my own direct Uint8Array->base64 implementation. I don't think you'll need that, but it's hereif you want to take a look; it's pretty neat.
我最近在浏览器中实现了tar。作为该过程的一部分,我制作了自己的直接 Uint8Array->base64 实现。我认为您不需要那个,但如果您想看一看,它就在这里;它很整洁。
What I do now:
我现在应该做什么:
The code for converting to string from a Uint8Array is pretty simple (where buf is a Uint8Array):
从 Uint8Array 转换为字符串的代码非常简单(其中 buf 是 Uint8Array):
function uint8ToString(buf) {
var i, length, out = '';
for (i = 0, length = buf.length; i < length; i += 1) {
out += String.fromCharCode(buf[i]);
}
return out;
}
From there, just do:
从那里,只需执行以下操作:
var base64 = btoa(uint8ToString(yourUint8Array));
var base64 = btoa(uint8ToString(yourUint8Array));
Base64 will now be a base64-encoded string, and it should upload just peachy. Try this if you want to double check before pushing:
Base64 现在将是一个 base64 编码的字符串,它应该只上传 peachy。如果你想在推送前仔细检查,试试这个:
window.open("data:application/octet-stream;base64," + base64);
window.open("data:application/octet-stream;base64," + base64);
This will download it as a file.
这会将其下载为文件。
Other info:
其他信息:
To get the data as a Uint8Array, look at the MDN docs:
要将数据作为 Uint8Array 获取,请查看 MDN 文档:
回答by Josef
My solution was use readAsBinaryString()
and btoa()
on its result.
我的解决办法是使用readAsBinaryString()
和btoa()
它的结果。
uploadFileToServer(event) {
var file = event.srcElement.files[0];
console.log(file);
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
console.log(btoa(reader.result));
};
reader.onerror = function() {
console.log('there are some problems');
};
}
回答by rozar
I used FileReader to display image on click of the file upload button not using any Ajax requests. Following is the code hope it might help some one.
我使用 FileReader 在不使用任何 Ajax 请求的情况下单击文件上传按钮来显示图像。以下是代码希望它可以帮助某人。
$(document).ready(function($) {
$.extend( true, jQuery.fn, {
imagePreview: function( options ){
var defaults = {};
if( options ){
$.extend( true, defaults, options );
}
$.each( this, function(){
var $this = $( this );
$this.bind( 'change', function( evt ){
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
$('#imageURL').attr('src',e.target.result);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
});
});
}
});
$( '#fileinput' ).imagePreview();
});
回答by Chris Nolet
After struggling with this myself, I've come to implement FileReader for browsers that support it (Chrome, Firefox and the as-yet unreleased Safari 6), and a PHP script that echos back POSTed file data as Base64-encoded data for the other browsers.
在自己为此苦苦挣扎之后,我开始为支持它的浏览器(Chrome、Firefox 和尚未发布的 Safari 6)实现 FileReader,以及一个 PHP 脚本,该脚本将已发布的文件数据作为 Base64 编码的数据回传给另一个浏览器。
回答by jordan.baucke
I've started to think that using the 'iframe' for Ajax style upload might be a much better choice for my situation until HTML5comes full circle and I don't have to support legacy browsers in my app!
我开始认为使用“iframe”进行 Ajax 样式上传可能是我的情况更好的选择,直到HTML5完整循环并且我不必在我的应用程序中支持旧版浏览器!