I'm writing a function to upload multiple files to AWS S3. Even with a single file, the commented code using TransferUtilityUploadRequest below fails with an error:
System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
The uncommented code works, (but I am unable to set ACL permissions). Having looked at several examples online, I am not sure what I am doing wrong? The RequestFormLimits are not this issue here, the code fails at the point it tries to upload to S3.
[HttpPost("test/raw-file-upload-s3")]
[RequestFormLimits(MultipartBodyLengthLimit = 1073741824)]
[RequestSizeLimit(1073741824)]
public async Task<ActionResult<object>> UploadFiles3(IList<IFormFile> files)
{
var regionEndpoint = RegionEndpoint.GetBySystemName(_awsS3RegionEndpoint);
var uploadedFileNames = new List<string>();
using (var awsS3Client = new AmazonS3Client(new BasicAWSCredentials(_awsAccessKeyId, _awsSecretKey), regionEndpoint))
{
using (var fileTransferUtility = new TransferUtility(awsS3Client))
{
var dateBasedDirectoryName = GetDateBasedDirectoryName();
string contentDirectory = $@"example/";
var tasks = new Task[files.Count];
var streams = new Stream[files.Count];
for (int i = 0; i < files.Count; i++)
{
string fileName = $"{Guid.NewGuid()}_{files[i].FileName}";
string key = $"{contentDirectory}{fileName}";
streams[i] = files[i].OpenReadStream();
tasks[i] = fileTransferUtility.UploadAsync(streams[i], _awsS3AssetsBucket, key);
// var fileTransferUtilityRequest = new TransferUtilityUploadRequest
// {
// BucketName = _awsS3AssetsBucket,
// Key = key,
// CannedACL = S3CannedACL.PublicRead,
// InputStream = streams[i]
// };
// tasks[i] = fileTransferUtility.UploadAsync(fileTransferUtilityRequest);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
for (int i = 0; i < files.Count; i++)
{
streams[i].Close();
}
}
}
return new
{
uploadedFiles = uploadedFileNames
};
}
Can you try below
// Set Canned ACL (PublicRead) for an existing item
client.PutACL(new PutACLRequest
{
BucketName = _awsS3AssetsBucket,
Key = key,
CannedACL = S3CannedACL.PublicRead
});
Before this line
tasks[i] = fileTransferUtility.UploadAsync(streams[i], _awsS3AssetsBucket, key);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.