I'm trying to upload an array of files to an s3 bucket. I'm building an array of promises for each file, that generates the pre-signed URL, blobs the file and then does the upload. Each promise should resolve once the upload is complete.
When all the uploads are complete, I try to refresh the page.
I'm attempting to do this with the following code:
async function uploadFiles() {
let requestArray = files.map(file => {
return new Promise(resolve => {
handleDocs.GenerateUrl(file.fileName, "{!OppName}", async (result, event) => {
let preSignedUrl = result.Data.toString().replace(/amp;/gm, "");
let blob = b64toBlob(file.fileString, result.ContentType);
await fetch(preSignedUrl, {
method: "PUT",
body: blob,
headers: {
"Content-Type": result.ContentType,
},
});
resolve();
});
});
});
await Promise.all(requestArray);
document.location.reload();
}
Where handleDocs.GenerateUrl
is calling:
@remoteAction
Public static UploadUrl GenerateUrl(string NewFileName, String OpportunityName){
NewFileName = NewFileName.deleteWhitespace();
String getEndpoint = ApiUrl + '/document'
+ '?OpportunityName='+ EncodingUtil.urlEncode(OpportunityName, 'utf-8')
+ '&FileName='+ EncodingUtil.urlEncode(NewFileName, 'utf-8');
HttpRequest request = new HttpRequest();
request.setEndpoint(getEndpoint);
request.setHeader('x-api-key', ApiKey);
request.setMethod('GET');
request.setHeader('Content-Type', 'application/json');
Http http = new Http();
HTTPResponse response = http.send(request);
return (UploadUrl)JSON.deserialize(response.getBody(), UploadUrl.class);
}
My guess is that the handleDocs.GenerateUrl
is behaving in a way that I don't understand, and I'm wiring the promises up incorrectly.
I've not been able to find any examples that solve a similar problem and that have worked for me.
The actual logic seems fine since the files do upload successfully most of the time. Is there any issue with how I'm building up the promises?
Any help would be appreciated!