0

I am trying to upload file directly to S3 with pre-signed URL, but can't get it working, checked all the related posts, but can't find any solution. I was able to upload via angular in another project, the below code is working.

const req = new HttpRequest('PUT', preSignedUrl, file, {
    reportProgress: true
});

$this._http.request(req).subscribe(e => {
    if (e.type === HttpEventType.UploadProgress) {
        ...
    } else if (e instanceof HttpResponse) {
        ...
    }
})

However, now i'm trying to get the same output with Ajax but I'm getting 403 Forbidden. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is the code thats not working:

$.ajax({
    type: 'PUT',
    url: preSignedUrl,
    // Content type must much with the parameter you signed your URL with
    headers: {
        "Content-Type": file.type,
        'x-amz-acl': 'public-read'
    },
    // this flag is important, if not set, it will try to send data as a form
    processData: false,
    // the actual file is sent raw
    data: file
})
    .success(function () {
        alert('File uploaded');
    })
    .error(function () {
        alert('File NOT uploaded');
        console.log(arguments);
    });

Please Help

awsaf
  • 11
  • 1
  • 3
  • Did you try to pass `crossDomain` as `true` in your ajax config object? It should work after that. – Ashish Jan 16 '18 at 09:58

1 Answers1

1

Please check : Upload a file with $.ajax to AWS S3 with a pre-signed url

 $.ajax({
      type: 'PUT',
      url: "<YOUR_PRE_SIGNED_UPLOAD_URL_HERE>",
      // Content type must much with the parameter you signed your URL with
      contentType: 'binary/octet-stream',
      // this flag is important, if not set, it will try to send data as a form
      processData: false,
      // the actual file is sent raw
      data: theFormFile
    })
    .success(function() {
      alert('File uploaded');
    })
    .error(function() {
      alert('File NOT uploaded');
      console.log( arguments);
    });

For Configure CORS in Browser : link

<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
    <ExposeHeader>ETag</ExposeHeader>
  </CORSRule>
</CORSConfiguration>
IftekharDani
  • 3,619
  • 1
  • 16
  • 21
  • You see this link : https://stackoverflow.com/questions/28568794/amazon-s3-javascript-no-access-control-allow-origin-header-is-present-on-the OR https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html For Enable cors in browser. – IftekharDani Jan 16 '18 at 10:21
  • i'm using pre signed url, the server is properly configured, as i can still upload via angular – awsaf Jan 17 '18 at 10:52
  • You missed `PUT`. I'm editing to add it. – Koushik Shom Choudhury Oct 16 '19 at 19:22