简体   繁体   中英

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

I have this 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:

[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. I have a known filename and all other information about the file. Now i give that information to my 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.

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

You could get the fielstream with IFormFile.OpenReadStream() method and get the base64string as below:

var fs=file.OpenReadStream();
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, bt.Length);
fs.Close();
var base64str=Convert.ToBase64String(bt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM