簡體   English   中英

為什么在上傳處理時我的 ASP.NET Core 7 MVC 中出現 FileNotFOund 異常?

[英]Why am I getting a FileNotFOund Exception in my ASP.NET Core 7 MVC while upload handling?

我有這個 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; }
}

我的聯系表將數據發送到我的 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" });
    }
}

目前 controller 擁有完整的 model 和一個附件。 我有一個已知的文件名和有關該文件的所有其他信息。 現在我將該信息提供給我的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",
                        },
                    };
                }
            }
        }
}

現在我收到一個“FileNotFound”異常,因為它在我的應用程序目錄src\MannsBlog\22060_CODE_1-2023_Web.pdf中查找。

但總的來說,我期望它會在我的下載目錄(我瀏覽的位置)中搜索。

我怎樣才能解決這個問題?

只是因為File.ReadAllText()需要路徑,如果你只是將文件的名稱傳遞給方法,它會將你當前的目錄與名稱結合起來構造一個新的絕對路徑

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM