【问题标题】:C# WebApi How can i get complete Image from HttpPostedFileC# WebApi 如何从 HttpPostedFile 获取完整的图像
【发布时间】:2018-10-07 14:22:10
【问题描述】:

我在这里使用 WebApi 我想要一张用于发送电子邮件的图像为此我将代码编写为:

var files = HttpContext.Current.Request.Files;
if (files.Count > 0) {
 for (int i = 0; i < files.Count; i++) {
  HttpPostedFile file = files[i];
  mailModel.filename = file.FileName;
  mailModel.filecontent = file.InputStream;
 }
}

这里如何绑定mailModel.Filecontent

我的类文件为

public class SendMailRequest
{
  public string filecontent { get; set; }
  public string filename { get; set; }
}

我的邮件发送代码是:

if (mailModel.filename != null) {
 string tempPath = WebConfigurationManager.AppSettings["TempFile"];

 string filePath = Path.Combine(tempPath, mailModel.filename);

 using(System.IO.FileStream reader = System.IO.File.Create(filePath)) {
  byte[] buffer = Convert.FromBase64String(mailModel.filecontent);
  reader.Write(buffer, 0, buffer.Length);
  reader.Dispose();
 }

 msg.Attachments.Add(new Attachment(filePath));

如何将我的文件绑定到 FileContent?

【问题讨论】:

  • mailModel.filecontent = file.InputStream; 这行肯定不行,因为InputStreamStream,而不是string
  • @PrashantPimpale 你有任何想法将 HttpPostedFile 转换为字符串.. 因为这里我需要 2 将数据转换为 Base64

标签: c# asp.net-web-api httppostedfilebase


【解决方案1】:

我想您可能想了解如何在 .Net 中使用 Streams?首先在这里使用 Stream 而不是字符串:

public class SendMailRequest
{
  public Stream FileContent { get; set; }
  public string FileName { get; set; }
}

然后,因为它完全令人困惑,请将您的 reader 重命名为 writer

然后,不要对您的 Stream 做任何严格的操作,只需这样做:

await mailModel.filecontent.CopyToAsync(writer);

这里有一个复杂的地方。此代码假定在您尝试发送电子邮件时,原始上传的文件流仍然存在并在内存中工作。这是否属实取决于两者之间发生的事情。

特别是,如果 Http 请求处理已经完成并且在电子邮件发送之前返回了响应,则文件内容流可能已经消失了。有一个更安全的方法是直接在控制器中进行复制:

file.InputStream.CopyToASync(mailModel.filecontent)

但此时我不得不说,我宁愿 (1) 直接复制到文件或 (2) 复制到 MemoryStream。即

mailModel.filecontent= new MemoryStream();
file.InputStream.CopyToASync(mailModel.filecontent)

(如果您使用 MemoryStream,则必须计算您愿意处理的最大文件是多少,并确保在创建内存流之前拒绝更大的文件)。

最后,如果这会使用 Base64 而不是二进制文件填充您的文件,请查看此问题的答案:HttpRequest files is empty when posting through HttpClient

【讨论】:

  • 当我像那样使用 mailModel.filecontent.CopyTo(file.InputStream);我收到错误,因为对象引用未设置为实例
  • 然后 (1) 在mailModel.filecontent = file.InputStream 行使用调试器来确定正在发布的文件是否真的是非空/非空 (2) 有一个复杂的情况,我会添加到我的答案中
  • mailModel.filecontent.CopyTo(file.InputStream) 不在您的原始代码中,也不在我的代码中。你是说file.InputStream.CopyTo(mailModel.filecontent) 吗?在这种情况下,必须首先创建并打开mailModel.filecontent
猜你喜欢
  • 2017-09-08
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 2018-08-28
相关资源
最近更新 更多