2012-11-08 2 views
7

amazon이 HTML5를 사용하여 CORS 업로드를 허용하지만 'html5'런타임을 사용하여 파일을 s3으로 푸시하도록 plupload를 성공적으로 구성한 사람이 있다는 점이 매우 관련된 질문 (Upload directly to Amazon S3 using Plupload HTML5 runtime)에서 언급 되었습니까? 관련 질문에 대한 응답은 구현 세부 사항을 제공하지 않습니다.'html5'런타임을 사용하여 s3에 직접 plupload를 구현하는 방법은 무엇입니까?

여기에 내 현재 plupload 구성입니다 : 위의 코드는 '플래시'실행을 위해 노력하고 있습니다

$("#uploader").plupload({ 
    // General settings 
    runtimes: 'html5,flash', 
    url: 'http://s3.amazonaws.com/' + $('#Bucket').val(), 
    max_file_size: '20mb', 
    multipart: true, 
    multipart_params: { 
     'key': '${filename}', // use filename as a key 
     'Filename': '${filename}', // adding this to keep consistency across the runtimes 
     'acl': $('#Acl').val(), 
     'Content-Type': 'binary/octet-stream', 
     'success_action_status': '201', 
     'AWSAccessKeyId': $('#AWSAccessKeyId').val(), 
     'policy': $('#Policy').val(), 
     'signature': $('#Signature').val() 
    }, 
    file_data_name: 'file', 
    multiple_queues: true, 
    filters: [ 
     { title: "Image files", extensions: "jpg,png,gif,jpeg" } 
    ], 
    flash_swf_url: '/Scripts/plupload/plupload.flash.swf', 
}); 

, 그래서 정책을 생성하고 올바르게 서명됩니다.

multipart_params 구성 객체에 인수가 누락 되었습니까? 또한

, 내 S3 버킷에 다음과 같은 CORS 구성을 사용하고 있습니다 :

<?xml version="1.0" encoding="UTF-8"?> 
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> 
    <CORSRule> 
     <AllowedOrigin>*</AllowedOrigin> 
     <AllowedMethod>PUT</AllowedMethod> 
     <AllowedMethod>POST</AllowedMethod> 
     <AllowedMethod>GET</AllowedMethod> 
     <AllowedMethod>HEAD</AllowedMethod> 
     <MaxAgeSeconds>3000</MaxAgeSeconds> 
     <AllowedHeader>*</AllowedHeader> 
    </CORSRule> 
</CORSConfiguration> 

나는 'HTML5'plupload 런타임에서 CORS 업로드를 허용하도록 S3 버킷에 다른 구성을 변경해야합니까?

답변

9

여기

var params = {}; 

     $('#uploader').pluploadQueue({ 
      runtimes: 'html5,flash', 
      flash_swf_url: '/js/plupload/1.5.4/plupload.flash.swf', // Have to load locally 
      url: 'https://s3.amazonaws.com/my-bucket-name', 
      multiple_queues: true, 
      preinit: { 
       UploadFile: function (up, file) { 
        up.settings.multipart_params = { 
         key: file.name, 
         filename: file.name, 
         AWSAccessKeyId: 'my-aws-access-key', 
         acl: 'private', 
         policy: params[file.name]["policy"], 
         signature: params[file.name]["signature"], 
         success_action_status: '201' 
        } 
       } 
      }, 
      init: { 
       FilesAdded: function (up, files) { 
        plupload.each(files, function (file) { 

         $.ajax({ 
          url: '/r/prepare_raw_upload', 
          type: 'post', 
          data: { 
           acl: 'private', 
           bucket: 'my-bucket-name', 
           file: file.name 
          }, 
          success: function (data) { 
           if (data.success) { 
            params[data.file] = { policy: data.policy, signature: data.signature }; 
           } 
           else if (data.message) { 
            alert(data.message); 
           } 
          } 
         }); 

        }); 
       } 
      } 
     }); 

당신은 내가 아약스 호출을 가지고있는 FilesAdded 이벤트 리스너에 알 수 있습니다 ... 난이 작동하도록하는 데 사용되는 정확한 코드입니다. 그러면 추가 된 각 파일에 대한 내 서버의 정책과 서명이 검색됩니다. 여기

는 ...이었다이 작품을 만드는

public static Dictionary<string, object> prepareUpload(DateTime now, string acl, string bucket, string key, string file) 
    { 
     Dictionary<string, object> result = new Dictionary<string, object>(); 
     ASCIIEncoding encoding = new ASCIIEncoding(); 

     string policy = createUploadPolicy(now, acl, bucket, key); 
     result.Add("policy", Convert.ToBase64String(encoding.GetBytes(policy))); 
     result.Add("signature", createUploadSignature(policy)); 
     result.Add("file", file); 

     return result; 
    } 

    public static string createUploadPolicy(DateTime now, string acl, string bucket, string key) 
    { 
     ASCIIEncoding encoding = new ASCIIEncoding(); 
     JavaScriptSerializer jss = new JavaScriptSerializer(); 

     Hashtable policy = new Hashtable(); 
     policy.Add("expiration", now.AddDays(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'")); 
     ArrayList conditions = new ArrayList(); 
     conditions.Add(new Hashtable { { "acl", acl } }); 
     conditions.Add(new Hashtable { { "bucket", bucket } }); 
     conditions.Add(new Hashtable { { "key", key } }); 
     conditions.Add(new ArrayList { "starts-with", "$name", "" }); 
     conditions.Add(new ArrayList { "starts-with", "$filename", "" }); 
     conditions.Add(new ArrayList { "starts-with", "$success_action_status", "" }); 
     policy.Add("conditions", conditions); 

     return jss.Serialize(policy); 
    } 

    public static string createUploadSignature(string policy) 
    { 
     ASCIIEncoding encoding = new ASCIIEncoding(); 
     byte[] policyBytes = encoding.GetBytes(policy); 
     string policyBase64 = Convert.ToBase64String(policyBytes); 

     byte[] secretKeyBytes = encoding.GetBytes(ConfigurationManager.AppSettings["AWSSecretKey"]); 
     HMACSHA1 hmacsha1 = new HMACSHA1(secretKeyBytes); 

     byte[] policyBase64Bytes = encoding.GetBytes(policyBase64); 
     byte[] signatureBytes = hmacsha1.ComputeHash(policyBase64Bytes); 

     return Convert.ToBase64String(signatureBytes); 
    } 

매우 유용한 링크를 정책 및 서명을 다시 전송 뒷면에있는 코드의

How do I make Plupload upload directly to Amazon S3?

http://codeonaboat.wordpress.com/2011/04/22/uploading-a-file-to-amazon-s3-using-an-asp-net-mvc-application-directly-from-the-users-browser/

+1

CORS 사용중인 구성도 괜찮아 보입니다. 내 모습이 그 것처럼 보입니다. – sunnymtn

+0

알았어요. 도움을 주셔서 감사합니다. – njebert

+0

@sunnymtn 완전한 코드를 보여줄 수 있습니까? njebert가 보여준 코드에 제공 한 코드를 구현하는 방법을 알지 못합니다. – SReca