How to upload to AWS S3 directly from browser using a pre-signed URL instead of credentials?

后端 未结 7 1164
天命终不由人
天命终不由人 2020-12-08 03:07

We\'d like to use Javascript AWS SDK to upload files to S3, but without using credentials at all. Uploading using credentials works, but we cannot generate an AWS IAM user f

7条回答
  •  不思量自难忘°
    2020-12-08 03:17

    If you're not using jQuery, this is the minimal you need on the front end:

    var xhr = new XMLHttpRequest();
    xhr.open('PUT', signedUrl, true);
    xhr.setRequestHeader('Content-Type', signedUrlContentType);
    xhr.onload = () => {
      if (xhr.status === 200) {
        // success!
      }
    };
    xhr.onerror = () => {
      // error...
    };
    xhr.send(file); // `file` is a File object here 
    

    See File object docs: https://developer.mozilla.org/en-US/docs/Web/API/File

    Then you can add your upload progress as usual:

    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) {
        var percent = Math.round((event.loaded / event.total) * 100)
        console.log(percent);
      }
    };
    

提交回复
热议问题