好的,在这个 phonegap 应用程序中,我从设备相机中的一个巨大图像文件开始。
然后我降低分辨率并允许用户使用 javascript canvas 和一些非常酷的代码 darkroomJS 来裁剪它。
最后,darkroomJS 使用 toDataURL() 方法从 Canvas 中获取 base64 数据。
现在我需要将它上传到 Amazon S3。
我可以使用表单将文件从我的计算机上传到 S3。我正在做的是发送 base64 数据。
我还有一个将 base64 数据转换为 blob 的函数。 (我读过的内容是必需的,但我愿意接受其他想法)。
<form action="https://mybucketname.s3.amazonaws.com/" method="post" enctype="multipart/form-data">
<input type="" id="key" name="key" value="uploads/${filename}">
<input type="" id="AWSAccessKeyId" name="AWSAccessKeyId" value="YOUR_AWS_ACCESS_KEY">
<input type="" id="acl" name="acl" value="private">
<!-- <input type="" id="success_action_redirect" name="success_action_redirect" value="http://localhost/"> -->
<input type="" id="policy" name="policy" value="YOUR_POLICY_DOCUMENT_BASE64_ENCODED">
<input type="" id="signature" name="signature" value="YOUR_CALCULATED_SIGNATURE">
<input type="" id="Content-Type" name="Content-Type" value="image/jpeg">
<!-- <input id="file" name="file" > -->
<br>
<input type="submit" value="Upload File to S3">
</form>
从我的服务器获取凭据后,我使用 jquery 写入凭据。那部分工作正常。
问题是如何将 blob 放入表单中?
我试过两种方法。 使用 jQuery 设置值。
$page.find("#file").attr('value', blobData); //将字符串 [object Blob] 文本插入字段并将其发送到 S3,不是很有用
我也试过:
var fd = new FormData(document.forms[0]);
fd.append('file', blobData);
//无效;然后 S3 提示它期待一个文件,但没有得到。
我做错了什么?我怎样才能使它工作?
最佳答案
好的,有一些有用的东西:
我想在页面上实际呈现表单会强制浏览器对 blob 进行字符串化。
函数 s3Man.getS3Policy 只是向我的服务器发出 AJAX 请求,以获取已签名的 s3 策略、 key 等。
this.uploadBase64ImgToS3 = function(base64Data, filename, callback){
var xmlhttp = new XMLHttpRequest();
var blobData = dataURItoBlob(base64Data);
var contentType = false;
if (filename.match(/.png/)) var contentType = 'image/png';
if (filename.match(/.jpg/)) contentType = 'image/jpeg';
if (!contentType){
xStat.rec("content type not determined, use suffix .png or .jpg");
return;
}
s3Man.getS3Policy(filename, function(s3Pkg){
console.log("policy:", s3Pkg);
var fd = new FormData();
fd.append('key', s3Pkg.filename);
fd.append('acl', 'public-read');
fd.append('Content-Type', contentType);
fd.append('AWSAccessKeyId', s3Pkg.awsKey);
fd.append('policy', s3Pkg.policy);
fd.append('signature', s3Pkg.signature);
fd.append("file", blobData);
xmlhttp.open('POST', 'https://swoopuploadspublic.s3.amazonaws.com/', true);
xmlhttp.send(fd);
});
}
关于javascript - 将 base64 图像数据上传到 Amazon S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23557848/