我在通过API Net Core将文件上传到s3时遇到问题。错误保持提示 System.Threading.Tasks.TaskCanceledException:任务已取消。
var response =等待amazonS3.PutObjectAsync(request);
我已经在可以工作的本地环境上进行了测试,并检查了凭据文件。一切似乎都很好。
[HttpPost("upload")]
[Authorize]
public async Task<IActionResult> Upload(MediaUploadResource resource)
{
if (resource.Files == null)
{
ModelState.AddModelError("no_file_input", "No file input received.");
return BadRequest(ModelState);
}
if (resource.Files.Sum(f => f.Length) < 1)
{
ModelState.AddModelError("no_file_input", "No file input received.");
return BadRequest(ModelState);
}
try
{
var returnValues = new MediaListResource();
PutObjectRequest request = new PutObjectRequest();
request.BucketName = options.Value.AwsS3BucketName;
request.CannedACL = S3CannedACL.Private;
foreach (var file in resource.Files)
{
if (file.Length < 1) continue;
var fileExtension = Path.GetExtension(file.FileName);
if (!defaultAllowedFileTypes.Contains(fileExtension))
{
returnValues.NotUploaded.Add(new MediaErrorResource
{
FileName = file.FileName,
Message = "Illegal file format. Format supported: " + String.Join(", ", defaultAllowedFileTypes)
});
}
var pathForSaving = String.Format("{0}{1}/{2}/{3}",
options.Value.MockAwsS3 ? "mock/" : String.Empty,
resource.Folder,
DateTime.Now.ToString("dMMyyHmmssfff"),
file.FileName
);
using (var ms = new MemoryStream())
{
await file.CopyToAsync(ms);
request.Key = pathForSaving;
request.InputStream = ms;
var response = await amazonS3.PutObjectAsync(request);
if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
{
returnValues.NotUploaded.Add(new MediaErrorResource
{
FileName = file.FileName,
Message = "Unexpected error. Status code: " + ((int)response.HttpStatusCode).ToString()
});
}
else
{
returnValues.Uploaded.Add(new MediaResource
{
Raw = pathForSaving,
Url = amazonS3.HashBucketObjectUrl(pathForSaving, options.Value.AwsS3BucketName, options.Value.AwsS3BucketFileValidMins),
FileName = file.FileName
});
}
}
}
return Ok(returnValues);
}
catch (Exception ex)
{
logger.LogError(ex, String.Format("{0} was unable to upload object to AWS bucket.", User.Identity.Name));
return StatusCode(500, "YPYPY" + ex);
}
}