我想从请求的表单数据中提取文本和文件,以附加到我的邮件草稿中。在客户端,我正在使用FormData
包含要发送到服务器的文件和文本正文。在服务器代码中,我正在使用MultipartMemoryStreamProvider
从其Contents
中提取文件并附加到草稿正文中,但是我不知道如何从中提取文本。我要去使用MultipartFormDataStreamProvider
,它具有FileData
和FormData
属性,但是我不知道要填写RootPath
。>
我是否可以从多部分表单数据中提取文件和文本,并使用文件或文本创建邮件草稿,而不必为每种情况编写不同的创建草稿功能?
这是服务器上的草稿功能:
[HttpPost]
[Route("createDraft")]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
public async Task<IHttpActionResult> CreateDraft(CancellationToken cancellationToken)
{
var service = await GoogleApis.GetGmailService(this, cancellationToken);
if (service == null)
{
return BadRequest("Haven't signed in google apis.");
}
MailMessage mailMessage = new MailMessage();
Draft draft = new Draft();
try
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
// extracting files
foreach (var file in provider.Contents)
{
Attachment attachedFile = new Attachment(await file.ReadAsStreamAsync(), file.Headers.ContentDisposition.FileName);
mailMessage.Attachments.Add(attachedFile);
}
mailMessage.Body = "abc" // <-- fill extracted text here
MimeMessage mimeMessage = MimeMessage.CreateFromMailMessage(mailMessage);
Message message = new Message
{
Raw = Encode(mimeMessage.ToString())
};
draft.Message = message;
var newDraft = service.Users.Drafts.Create(draft, "me").Execute();
return Ok(provider.Contents);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
在客户端上创建草稿功能:
createDraft() {
var fd = new FormData();
for (let i = 0; i < this.selectedFiles.length; i++) {
var f = this.selectedFiles[i];
fd.append("files", f, f.name);
}
fd.set('body', this.htmlBody); // <-- draft body
// htmlBody: text from input field
if (this.recipientsTo.length > 0) {
this.isLoadingResults = true;
this.mailService.createDraft(fd).subscribe(result => {
this.isLoadingResults = false;
this.dialogRef.close();
}, error => {
console.error(error);
});
}
else {
this.isLoadingResults = false;
this.dialogRef.close();
}
}
邮件创建草稿服务:
createDraft(draftBody) {
return this.http.post('/api/emails/createDraft', draftBody);
}