【问题标题】:Uploading file - ASP.NET Core MVC上传文件 - ASP.NET Core MVC
【发布时间】:2018-10-30 14:02:47
【问题描述】:

我的 ASP.NET Core 项目中有一个联系表单,它可以正常工作。但是现在,我想上传一个文件。这是我的代码:

型号:

namespace WebApplication1.Models
{
    public class MailModels
    {
        [StringLength(5)]
        public string Name { get; set; }
        [StringLength(5)]
        public string SurName { get; set; }
        //[StringLength(5, ErrorMessage = "First name cannot be longer than 50 characters.")]

        public string Email { get; set; }
        public string Telephone { get; set; }
        [StringLength(1000)]
        public string Message { get; set; }
        public IFormFile FileUploading { get; set; }
    }
}

视图(部分视图):

<label class="file_uploading">
    @Html.TextBoxFor(m => m.FileUploading, new { type = "file", @class = "input-file" })
</label>

控制器(控制器的一部分):

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index2(MailModels e, IFormFile file)
{
    if (ModelState.IsValid)
    {
        StringBuilder message = new StringBuilder();
        MailAddress from = new MailAddress(e.Email.ToString());
        message.Append("Name: " + e.Name + "\n");
        message.Append("Surname: " + e.SurName + "\n");
        message.Append("Email: " + e.Email + "\n");
        message.Append("Telephone: " + e.Telephone + "\n\n\n");
        message.Append("Text: " + e.Message + "\n");

        MailMessage mail = new MailMessage();
        SmtpClient smtp = new SmtpClient();
        // .....

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及重现它所需的最短代码在问题本身。没有明确的问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example
  • ...那么这里有什么问题?
  • 我的问题是如何发送上传文件以及其他信息,如姓名、姓氏、电子邮件、电话、文本..我不知道如何导入文件内容以及如何发送..
  • 从您的 POST 方法中删除无意义的 IFormFile file 参数,该参数将始终为 null(您的文件输入绑定到模型的 FileUploading 属性)

标签: .net asp.net-mvc asp.net-core-mvc asp.net-core-mvc-2.0


【解决方案1】:

首先,将MailModels e从参数中去掉,check this tutorial作为完整参考

编辑1:
您的代码应如下所示:

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);

// full path to file in temp location
var filePath = Path.GetTempFileName();

foreach (var formFile in files)
{
    if (formFile.Length > 0)
    {
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await formFile.CopyToAsync(stream);
        }
    }
}

// process uploaded files
// Don't rely on or trust the FileName property without validation.

return Ok(new { count = files.Count, size, filePath});
}

你的表格应该是这样的:

&lt;form method="post" enctype="multipart/form-data" asp-controller="UploadFiles" asp-action="Index"&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2011-07-08
    • 2013-06-10
    • 1970-01-01
    相关资源
    最近更新 更多