最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uploading file to S3 using a pre-signed URL - Stack Overflow

programmeradmin2浏览0评论

I'm trying to upload a file in my s3 bucket with an AWS pre-signed URL.

Here is my JS function:

function UploadObjectUsingPresignedURL() {
    var file = document.getElementById('customFile').files[0];
    console.log(file);
    var xhr = new XMLHttpRequest();
    xhr.open('PUT', 'hereMyPresignedURL', true);
    //xhr.setRequestHeader('Content-Type', 'image/jpeg');
    xhr.onload = () => {
      if (xhr.status === 200) {
        console.log('Uploaded data successfully');
      }
    };
    xhr.onerror = () => {
      console.log('Nope')
    };
    xhr.send(file); // `file` is a File object here 
}

Here is my HTML:

<div class="input-group">
    <div class="custom-file">
        <input type="file" class="custom-file-input" id="customFile"
            aria-describedby="customFile">
        <label class="custom-file-label" for="customFile">Choose file</label>
    </div>
    <div class="input-group-append">
        <button class="btn btn-outline-secondary" type="button" id="customFile" 
        onclick="UploadObjectUsingPresignedURL()">Button</button>
    </div>
</div>

And here the result in my console...

functions.js:4 File {name: "aragorn.jpg", lastModified: 1590136296908, lastModifiedDate: Fri May 22 2020 10:31:36 GMT+0200 (heure d’été d’Europe centrale), webkitRelativePath: "", size: 7714, …} functions.js:10 Uploaded data successfully)

So it seems it went well (Uploaded data successfully), but in my S3 bucket I have no new files... since I have no error, I don't know how to debug this.

Here is my .NET code for generating the pre-signed URL:

public static string MakeS3PresignedURIUpload() {
    string awsAccessKeyId = "XXX";
    string awsSecretAccessKey = "XXX";
    string s3Bucket = "test-bucket";
    string s3Key = "/aragorn.jpg";
    string awsRegion = "us-west-2";


    string presignedUri = "Error : No S3 URI found!";
    int expirationMinutes = 60;

    if (s3Bucket != String.Empty && s3Key != String.Empty && awsRegion != String.Empty) {
        try {
            s3Key = s3Key.Replace("\\", "/");
            GetPreSignedUrlRequest presignedUriReq = new GetPreSignedUrlRequest();
            RegionEndpoint myRegion = RegionEndpoint.GetBySystemName(awsRegion);
            AmazonS3Client client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, myRegion);
            presignedUriReq.Verb = HttpVerb.PUT;
            presignedUriReq.BucketName = s3Bucket;
            presignedUriReq.Key = s3Key;
            presignedUriReq.Expires = DateTime.UtcNow.AddMinutes(expirationMinutes);
            presignedUri = client.GetPreSignedURL(presignedUriReq); }
        catch (AmazonS3Exception e) {
            return string.Format("Error : S3 - MakeS3PresignedURIUpload - Error encountered on server.Message:'{0}' when writing an object", e.Message);
        }
        catch (Exception e) {
            return string.Format("Error : S3 - MakeS3PresignedURIUpload - Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
        }
    }
    return presignedUri;
}

I'm trying to upload a file in my s3 bucket with an AWS pre-signed URL.

Here is my JS function:

function UploadObjectUsingPresignedURL() {
    var file = document.getElementById('customFile').files[0];
    console.log(file);
    var xhr = new XMLHttpRequest();
    xhr.open('PUT', 'hereMyPresignedURL', true);
    //xhr.setRequestHeader('Content-Type', 'image/jpeg');
    xhr.onload = () => {
      if (xhr.status === 200) {
        console.log('Uploaded data successfully');
      }
    };
    xhr.onerror = () => {
      console.log('Nope')
    };
    xhr.send(file); // `file` is a File object here 
}

Here is my HTML:

<div class="input-group">
    <div class="custom-file">
        <input type="file" class="custom-file-input" id="customFile"
            aria-describedby="customFile">
        <label class="custom-file-label" for="customFile">Choose file</label>
    </div>
    <div class="input-group-append">
        <button class="btn btn-outline-secondary" type="button" id="customFile" 
        onclick="UploadObjectUsingPresignedURL()">Button</button>
    </div>
</div>

And here the result in my console...

functions.js:4 File {name: "aragorn.jpg", lastModified: 1590136296908, lastModifiedDate: Fri May 22 2020 10:31:36 GMT+0200 (heure d’été d’Europe centrale), webkitRelativePath: "", size: 7714, …} functions.js:10 Uploaded data successfully)

So it seems it went well (Uploaded data successfully), but in my S3 bucket I have no new files... since I have no error, I don't know how to debug this.

Here is my .NET code for generating the pre-signed URL:

public static string MakeS3PresignedURIUpload() {
    string awsAccessKeyId = "XXX";
    string awsSecretAccessKey = "XXX";
    string s3Bucket = "test-bucket";
    string s3Key = "/aragorn.jpg";
    string awsRegion = "us-west-2";


    string presignedUri = "Error : No S3 URI found!";
    int expirationMinutes = 60;

    if (s3Bucket != String.Empty && s3Key != String.Empty && awsRegion != String.Empty) {
        try {
            s3Key = s3Key.Replace("\\", "/");
            GetPreSignedUrlRequest presignedUriReq = new GetPreSignedUrlRequest();
            RegionEndpoint myRegion = RegionEndpoint.GetBySystemName(awsRegion);
            AmazonS3Client client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, myRegion);
            presignedUriReq.Verb = HttpVerb.PUT;
            presignedUriReq.BucketName = s3Bucket;
            presignedUriReq.Key = s3Key;
            presignedUriReq.Expires = DateTime.UtcNow.AddMinutes(expirationMinutes);
            presignedUri = client.GetPreSignedURL(presignedUriReq); }
        catch (AmazonS3Exception e) {
            return string.Format("Error : S3 - MakeS3PresignedURIUpload - Error encountered on server.Message:'{0}' when writing an object", e.Message);
        }
        catch (Exception e) {
            return string.Format("Error : S3 - MakeS3PresignedURIUpload - Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
        }
    }
    return presignedUri;
}
Share Improve this question edited Mar 1, 2022 at 17:12 TylerH 21.1k79 gold badges79 silver badges114 bronze badges asked Jun 11, 2020 at 10:12 Paul DuboisPaul Dubois 711 gold badge1 silver badge8 bronze badges 6
  • maybe also console.log(xhr.responseText) to find out more about the response from aws? Are you using the AWS S3 console to view the files? – wschopohl Commented Jun 11, 2020 at 10:26
  • @wschopohl Thanks for your ment :) Yes I use s3.console.aws.amazon. to view the files. I just try console.log(xhr.responseText) and console.log(xhr.response) and both are empty ... What does that mean ? – Paul Dubois Commented Jun 11, 2020 at 10:34
  • Hmm, I think it should mean it worked, like you said.. How are you generating the presignedUrl? I think you need to set a 'Content-Type' Request Header in your presignedUrl code and in you xml request.. – wschopohl Commented Jun 11, 2020 at 10:59
  • @wschopohl I added in the post the function for generate the presigned-URL. It's just for test so I just run this .NET project in the console, and I copy/paste the returned URL in my JS project. But if I add a Content-Type, I can only send the same type of file ? If I want to send a jpg file and then a pdf file ? – Paul Dubois Commented Jun 11, 2020 at 11:57
  • From what I read it is important to set ContentType in your .NET code and in your js code, maybe give it a try! Apart from that I think you need a new presigned url for any new file put request anyway .. – wschopohl Commented Jun 11, 2020 at 12:46
 |  Show 1 more ment

1 Answer 1

Reset to default 3
string s3Key = "/aragorn.jpg";

Change to

string s3Key = "aragorn.jpg";

It was working, but saving the file in an un-named folder in the bucket and not directly in the bucket ...

发布评论

评论列表(0)

  1. 暂无评论