dwa*_*wat 3 javascript ajax html5 form-data trigger.io
我正在尝试将我的Trigger.io移动应用程序中的图像文件直接上传到Amazon S3(请参阅此处:http://aws.amazon.com/articles/1434).我可以在网上这样做,使用jQuery和FormDataAPI 没有任何问题,如下所示:
var fd = new FormData();
key = 'test.jpg'
fd.append('key', key);
fd.append('acl', 'public-read');
fd.append('Content-Type', file.type);
fd.append('AWSAccessKeyId', key_id);
fd.append('policy', policy_base64);
fd.append('signature', signature);
fd.append('file', file);
$.ajax({
type: 'POST',
url: 'https://' + bucket + '.s3.amazonaws.com/',
processData: false, // Not supported with Trigger
contentType: false, // Not supported with Trigger
data: fd,
success: function(response) {
// It worked...
}
});
Run Code Online (Sandbox Code Playgroud)
但是,我无法使用Forge请求API.这是我尝试过的:
forge.request.ajax({
type: 'POST',
url: 'https://' + bucket + '.s3.amazonaws.com/',
fileUploadMethod: 'raw',
files: [file],
data: fd,
headers: { 'Content-Type': 'multipart/form-data', 'x-amz-acl': 'public-read' },
success: function(response) {
// It worked...
}
});
Run Code Online (Sandbox Code Playgroud)
但是,我从亚马逊收到以下错误:
<Code>PreconditionFailed</Code>
<Message>At least one of the pre-conditions you specified did not hold</Message>
<Condition>Bucket POST must be of the enclosure-type multipart/form-data</Condition>
Run Code Online (Sandbox Code Playgroud)
我会forge.request完全支持这个$.ajax,但我file使用Forge File API检索并且只显示在S3上[object Object](我假设因为它是Forge文件,而不是来自HTML的真实文件对象<input />).
那么,如何使用FormDataForge API将Trigger.io中的文件上传到Amazon S3 ?任何帮助是极大的赞赏!谢谢!
您可以使用jQuery ajax $.ajax函数和FormDataJavaScript API将图像文件从Trigger.io移动应用程序直接上传到Amazon S3,就像在Web上一样.
您需要执行以下步骤:
forge.fileAPI 检索您的文件.forge.file.base64以返回文件内容的base64值.Blob从返回的base64值创建JavaScript 对象Blob对象附加到FormData对象$.ajax函数调用POST到Amazon S3的文件例如,一旦检索到图像文件(步骤1),就可以使用以下uploadImage功能将图像上传到Amazon S3:
function uploadImage(file, awsAccessKeyId, policy, signature, bucket) {
forge.file.base64(file, function (base64String) {
// Create a Blob from a base64 string
var byteCharacters = atob(base64String);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray.buffer], {type: "image/jpeg"});
var fd = new FormData();
fd.append('key', 'test.jpg');
fd.append('acl', 'public-read');
fd.append('Content-Type', 'image/jpeg');
fd.append('AWSAccessKeyId', awsAccessKeyId);
fd.append('policy', policy);
fd.append('signature', signature);
fd.append("file", blob);
$.ajax({
type: 'POST',
url: 'http://' + bucket + '.s3.amazonaws.com/',
processData: false,
contentType: false,
data: fd,
success: function(response) {
alert('Success uploading photo');
},
error: function () {
alert('Problem uploading photo');
}
});
});
}
Run Code Online (Sandbox Code Playgroud)