简体   繁体   English

无法上传文件asp.net mvc

[英]Cant upload file asp.net mvc

I am trying to upload file in asp.net MVC but the problem is that I cant get the file from the Request.Files[] 我正在尝试在asp.net MVC中上传文件,但问题是我无法从Request.Files[]获取文件

this is the controller side 这是控制器端

    [AllowAnonymous]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ValidateAndSignUp(ForCompany newCompany)
    {
        if (ModelState.IsValid)
        {

            company NewCompany = new company();
            TryUpdateModel(NewCompany);
            context.companies.Add(NewCompany);
            string token = new Hash().CalculateMD5Hash(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            if (context.companies.Any(com => com.Email == newCompany.Email.Trim()))
            {
                TempData["message"] = "<div class='error'>This email is already registered " + Request.Files.Count + " </div>";
            }
            else
            {
                uploadFile(Request.Files[0]);
                context.oneTimeAuthenticationTickets.Add(new oneTimeAuthenticationTicket { company_id = NewCompany.company_id, ticket = token, status = "v", DateOfCreation = DateTime.Now});
                context.SaveChanges();
                TempData["message"] = new Email() { To = newCompany.Email, From = "hworkflowteam@workflow.com", Subject = "New company with this email has been created", Body = "Please follow this <a href = 'http://localhost:49525//Accounts/validateNew/?token=" + token + "'>link</a> to validate your account and to create the first user" }.sendMail();

            }
            return RedirectToAction("signIn", "Accounts");
        }
        else
        {
            return View("signUp", newCompany);
        }
    }

      public void  uploadFile (HttpPostedFileBase file)
      {
          if (file.ContentLength > 0)
          {
              var fileName = Path.GetFileName(file.FileName);
              var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
              file.SaveAs(path);
          }
      }

here is the view side 这是风景区

@model workflow.DataHolders.ForCompany
<link href="@Url.Content("~/sharedfiles/css/forms/addnew.css")" rel="stylesheet" type="text/css" />

<div id="Add_container">
    <div class="message">If your company is already registered and  has not been verified or there are no users created, please <a href="@Url.getBaseUrl()/Accounts/VerifyAccount">click</a>  to  configure your account</div>

    @if (!ViewData.ModelState.IsValid)
    {
        <div id="validationMessage">Please Correct The Errors Below</div>
    }


    @using (Html.BeginForm("ValidateAndSignUp", "Accounts", FormMethod.Post))
    {
        @Html.AntiForgeryToken()

        @Html.ValidationMessage("CompanyName");
        <span class="field_title">Company Name: </span>
        @Html.TextBox("CompanyName")   

        @Html.ValidationMessage("Email");
        <span class="field_title">Email: </span>
        @Html.TextBox("Email")

        @Html.ValidationMessage("Country");
        <span class="field_title">Country Name: </span>
        @Html.DropDownList("Country", Model.Countries)

        <span class="field_title">About The Company: </span>
        @Html.TextArea("Description")

        <span class="field_title">Choose Company Logo</span>
        @Html.TextBox("Logo", Model.Logo, new { type = "file" })

        <input type="submit" value="Create New Account">


    }
</div>
<div class="get_connected_message">
    <h1>Get Connected with your Customers</h1>
</div>

<div class="get_connected_message">
    <h1>Build your profissional buisness world</h1>
</div>

<div class="clear"></div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

and here is the POCO that I use 这是我使用的POCO

public class ForCompany : DataHolder
{
    [Required]
    [StringLength(200, MinimumLength = 3, ErrorMessage = "Length Of The Company Name Should  Be More Than Three Letters")]
    public string CompanyName { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }

    [Required]
    public int Country { get; set; }

    public string Description { get; set; }

    public string Logo { get; set; }

    public List<SelectListItem> Countries { get; set; }

}

but when I try to upload the file I get OutOfRange Exception, so please could anyone help me to solve this problem. 但是当我尝试上传文件时,出现OutOfRange异常,因此请任何人帮助我解决此问题。

You just need to add enctype = "multipart/form-data" to your begin form like so 您只需要像这样将enctype = "multipart/form-data"到开始表单中

@using (Html.BeginForm("ValidateAndSignUp", "Accounts", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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