我需要获取要保存的电子邮件中的附件,我根据需要完成读取电子邮件和保存的整个过程,但当我试图获取要保存在AWS S3 Bucket中的附件时,它在尝试读取内容类型时会出错。基本上我需要做的是。
- 获取附件
- 为我的S3保存函数创建一个FormFile来保存附件(S3保存函数已经在工作(。我在构建FormFile时遇到了问题
.
.
.
var attachmentsToS3 = new FormFileCollection();
foreach (var attachment in message.Attachments)
{
var part = attachment as MimePart;
var stream = new MemoryStream();
await part.Content.DecodeToAsync(stream);
var fileLength = stream.Length;
var formFile = new FormFile(stream, 0, fileLength, "file[]", attachment.ContentDisposition.FileName);
attachmentsToS3.Add(formFile);
}
await _atendimentoServices.SaveAnexoAtendimentoToS3( attachmentsToS3, idAcompanhamento, requestApi);
.
.
.
更新
根据布鲁诺的回答所做的更改,现在正在发挥作用。
var attachmentsToS3 = new FormFileCollection();
foreach (MimeEntity attachment in message.Attachments)
{
var memory = new MemoryStream();
if (attachment is MimePart part)
await part.Content.DecodeToAsync(memory);
else
await ((MessagePart)attachment).Message.WriteToAsync(memory);
var bytes = memory.ToArray();
var contentType = MimeTypes.GetMimeType(attachment.ContentType.MimeType);
var formFile = new FormFile(memory, 0, bytes.Length, "file[]", attachment.ContentDisposition.FileName)
{
Headers = new HeaderDictionary(),
ContentType = contentType
};
attachmentsToS3.Add(formFile);
}
await _atendimentoServices.SaveAnexoAtendimentoToS3(attachmentsToS3, idAcompanhamento, requestApi);```
下午好,Gabriel,在分析您的代码时,我注意到代码中缺少了一些部分。
第一个你需要把你的依恋变成这样:
if (attachment is MimePart part) await part.Content.DecodeToAsync(memory);
else await ((MessagePart)attachment).Message.WriteToAsync(memory);
这样你就可以保证你的流是否被正确地填充为mimeType。
缺少的另一部分是FormFile构造函数中的标头和内容类型,请尝试。
var formFile = new FormFile(memory, 0, bytes.Length, "file[]", attachment.ContentDisposition.FileName)
{
Headers = new HeaderDictionary(),
ContentType = MimeTypes.GetMimeType(attachment.ContentType.MimeType);
};