[英]Why am I getting a FileNotFOund Exception in my ASP.NET Core 7 MVC while upload handling?
I have this model:我有这个 model:
public class ContactFormModel
{
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[StringLength(4096, ErrorMessage = "Your message is too long. Please shorten it to max. 4096 chars.")]
[MinLength(5)]
[Required]
public string Body { get; set; } = string.Empty;
[Required]
[StringLength(100, ErrorMessage = "Name is too long. Just 100 chars allowed.")]
public string Name { get; set; } = string.Empty;
[Required]
[StringLength(150, ErrorMessage = "Subject too long. Just 150 chars allowed.")]
public string Subject { get; set; } = string.Empty;
public IList<IFormFile>? Attachment { get; set; }
}
My contact form sends the data to my Controller:我的联系表将数据发送到我的 Controller:
[HttpPost("contact")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Contact(ContactFormModel model)
{
try
{
if (ModelState.IsValid)
{
var spamState = VerifyNoSpam(model);
if (!spamState.Success)
{
return BadRequest(new { Reason = spamState.Reason });
}
if (model?.Attachment?.Count > 0)
{
await _mailService.SendMailAsync("ContactTemplate.txt", model.Name, model.Email, model.Subject, model.Body, model.Attachment);
}
else
{
await _mailService.SendMailAsync("ContactTemplate.txt", model.Name, model.Email, model.Subject, model.Body);
}
_logger.LogDebug("Sent email.");
return View("EmailSent");
}
else
{
return BadRequest(new { Reason = "It looks like one or more information you entered was not valid." });
}
}
catch (Exception ex)
{
_logger.LogError("Failed to send email from contact page", ex);
return BadRequest(new { Reason = "Error Occurred" });
}
}
Currently the controller holds the full model with one attachment.目前 controller 拥有完整的 model 和一个附件。 I have a known filename and all other information about the file.
我有一个已知的文件名和有关该文件的所有其他信息。 Now i give that information to my
Emailservice
:现在我将该信息提供给我的
Emailservice
:
public async Task<bool> SendMailAsync(string template, string name, string email, string subject, string msg, [Optional] IList<IFormFile> attachment)
{
try
{
...
if (attachment != null)
{
this.logger.LogInformation("Attempting to send mail via SendGrid with attachment");
foreach (var attachmentItem in attachment)
{
string fileName = Path.GetFileName(attachmentItem.FileName);
Exception --> byte[] byteData = Encoding.ASCII.GetBytes(File.ReadAllText(fileName));
mailMsg.Attachments = new List<Attachment>
{
new Attachment
{
Content = Convert.ToBase64String(byteData),
Filename = fileName,
Disposition = "attachment",
},
};
}
}
}
}
Now I'm getting a "FileNotFound" exception because it looks in src\MannsBlog\22060_CODE_1-2023_Web.pdf
my application directory.现在我收到一个“FileNotFound”异常,因为它在我的应用程序目录
src\MannsBlog\22060_CODE_1-2023_Web.pdf
中查找。
But in general I'm expecting, that it searches in my download dir (where I browsed to).但总的来说,我期望它会在我的下载目录(我浏览的位置)中搜索。
How can I fix this?我怎样才能解决这个问题?
just because File.ReadAllText()
requires the path,if you just pass the name of the file to the method,it would combine your current Directory with the name to construct a new absolute path只是因为
File.ReadAllText()
需要路径,如果你只是将文件的名称传递给方法,它会将你当前的目录与名称结合起来构造一个新的绝对路径
You could get the fielstream with IFormFile.OpenReadStream()
method and get the base64string as below:您可以使用
IFormFile.OpenReadStream()
方法获取 fielstream 并获取 base64string,如下所示:
var fs=file.OpenReadStream();
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, bt.Length);
fs.Close();
var base64str=Convert.ToBase64String(bt);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.