将Base64图像数据上传到Amazon S3

3

好的,在这个PhoneGap应用程序中,我从设备相机获取一个巨大的图像文件。
然后我降低了分辨率,并允许用户使用JavaScript画布和一些非常酷的代码(称为darkroomJS)进行裁剪。 最后,darkroomJS使用toDataURL()方法从画布中获取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会抱怨它期望得到一个文件,但实际上没有收到。

我做错了什么?我该如何使其生效?

1个回答

3

好的,我有一些可以使用的内容:

我想表明,在页面上呈现表单会迫使浏览器将 blob 转换为字符串。
函数 s3Man.getS3Policy 只是向我的服务器发出 AJAX 请求以获取签名的 s3 策略、密钥等。

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);
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接