简体   繁体   中英

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[]

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

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.

You just need to add enctype = "multipart/form-data" to your begin form like so

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

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