Get properties of an ASP.NET file Razor C #

0

Hello, I'm doing a module in ASP.NET with Razor and C # where I upload a file of any type to a database , along with other data. I need to get the properties of the file on the server side ("with C # "), in order to be able to append these new data in my query to have them in the table. This is the error that appears to me when I try to get the data.



This is my client and server side code.

[HttpPost]
public ActionResult KyoTest(testsoru test) {

  string constr = "Data Source=DMX87025;Initial Catalog=DB_PCC;Integrated Security=True";

  HttpFileCollection files = test.Files;



  foreach(string fileTagName in files){
  
    HttpPostedFile file = test.Files[fileTagName];
    if (file.ContentLength > 0) {
      
      int size = file.ContentLength;
      string fname = file.FileName;
      int position = fname.LastIndexOf("\");
      fname = fname.Substring(position + 1);

      string contentType = file.ContentType;
      byte[] fileData = new byte[size];
      file.InputStream.Read(fileData, 0, size);


      using(SqlConnection con = new SqlConnection(constr)) {
        string query = "INSERT INTO Testsoru(Name, Wiw, Formato)" +
          " VALUES(@Name,@wiw,@format,@Size,@FName,@Type)";

        using(SqlCommand cmd = new SqlCommand(query)) {

          cmd.Connection = con;
          cmd.Parameters.AddWithValue("@Name", test.name);
          cmd.Parameters.AddWithValue("@wiw", test.wiw);
          cmd.Parameters.AddWithValue("@format", test.formato);
          cmd.Parameters.AddWithValue("@Size", size);
          cmd.Parameters.AddWithValue("@FName", fname);
          cmd.Parameters.AddWithValue("@Type", contentType);
          con.Open();
          cmd.ExecuteNonQuery();
          con.Close();
          con.Close();
        }
      }


    }
  }


  return View(test);
}
@using (Html.BeginForm("KyoTest", "Home", FormMethod.Post)) {
<table class="table table-hover" cellpadding="0" cellspacing="0">
  <tr>
    <th colspan="2" align="center">Customer Details</th>
  </tr>
  <tr>
    <td>Name: </td>
    <td>
      @Html.TextBoxFor(m => m.name)
    </td>
  </tr>
  <tr>
    <td>
      @Html.TextBoxFor(m => m.formato, new { type = "file" })
    </td>
  </tr>
  <tr>
    <td>Gender: </td>
    <td>
      @Html.DropDownListFor(m => m.wiw, new List
      <SelectListItem>
        { new SelectListItem{Text="India", Value="India"}, new SelectListItem{Text="China", Value="China"}, new SelectListItem{Text="Australia", Value="Australia"}, new SelectListItem{Text="France", Value="France"}, new SelectListItem{Text="Unites States", Value="Unites
        States"}, new SelectListItem{Text="Russia", Value="Russia"}, new SelectListItem{Text="Canada", Value="Canada"}}, "Please select")
    </td>
  </tr>
  <tr>
    <td></td>
    <td><input type="submit" value="Submit" /></td>
  </tr>
</table>
}

Thank you very much everyone for your support and your time :)
This is my ajax that I changed and with which I try to execute the same method of C #

< script >
  function trymeplz() {
    var object = {};
    object.namePro = $("[id*=name]").val();
    object.file = $('#format').prop("files")[0];
    object.wiw = document.getElementById("wiw").value;

    alert("{'namePro' : '" + object.namePro + "'," +
      "'file' : '" + object.file + "' ," +
      "'wiw' : '" + object.wiw + "'" +
      "}");

    $.ajax({
      type: "POST",
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      url: '@Url.Action("KyoTest", "Home")',
      data: "{'namePro' : '" + object.namePro + "'," +
        "'file' : '" + object.file + "' ," +
        "'wiw' : '" + object.wiw + "'" +
        "}",
      success: function(response) {
        alert("at least Ajax looks fine" + response);
      },
      Error: function(response) {

        alert("something got wrong" + response);
      }
    });
  } <
  /script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class=row "">
    <div class="col-lg-6">
      <table class="table table-hover">
        <thead>
          <tr>
            <th>Firstname</th>
            <th>Lastname</th>

          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Nombre</td>
            <td>
              <input type="text" placeholder="NombreDeProyecto" id="name" />
            </td>

          </tr>
          <tr>
            <td>Formato</td>
            <td>
              <label>Formato: </label> <input type="file" id="format" />
            </td>

          </tr>
          <tr>
            <td>Wiw</td>
            <td>
              <p>
                @Session["Wiw"]
                <input type="text" class="hidden" id="wiw" value="@Session[" WiW "]" />
              </p>
            </td>

          </tr>
          <tr>
            <td>
              <input type="button" onclick="trymeplz()" name="name" value="trymeplz" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="col-lg-6"></div>
  </div>
</div>
    
asked by E.Rawrdríguez.Ophanim 27.10.2017 в 19:16
source

2 answers

2

After reviewing your code in detail, I found some things to fix.

Sight Code:

@Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })

Controller Code:

[HttpPost]
public ActionResult KyoTest(testsoru test, HttpPostedFileBase[] files) 
{
    string constr = "Data Source=DMX87025;Initial Catalog=DB_PCC;Integrated Security=True";

    foreach (HttpPostedFileBase file in files)  
    {
        //...Aquí va el resto de tu código
    } 
}
    
answered by 27.10.2017 / 22:03
source
1

Many comments on your solution, so I'll try to take it step by step.

-In Asp .Net MVC there is what is called model binding (not necessarily always used), which basically consists in converting the value sent from the html fields of the form to the properties with the same name in the object . So, if you have an html field of type input ( with name="format" )

<input class="form-control" id="file" name="file" type="file" value="">

when doing the model binding in the action method, the value that comes in the property of the object called 'file'

-As you already commented, when sending files you have to indicate that the form html send bytes adding the enctype part:

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

-Most probably you come from Asp .Net, because of what you are using

HttpFileCollection files = test.Files;

in Asp .Net MVC the files are of type HttpPostedFileWrapper.

public HttpPostedFileWrapper file { get; set; }

- Finally, I leave a code that I think can help you understand (in it I even use bootstrap to give you better view):

The view:

@model UploadFiles.Models.testsoru

@using (Html.BeginForm("KyoTest", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-horizontal">
    <h4>Customer Details</h4>
    <hr />
    <div class="form-group">
        @Html.LabelFor(m => m.name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(m => m.name, new { htmlAttributes = new { @class = "form-control" } })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.formato, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(m => m.formato, new { htmlAttributes = new { @class = "form-control" } })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.file, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.file, new { type = "file", @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.wiw, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.wiw, ViewBag.List as List<SelectListItem>, "Please select", new { @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

The method of action:

    [HttpPost]
    public ActionResult KyoTest(testsoru test)
    {
        string constr = "Data Source=DMX87025;Initial Catalog=DB_PCC;Integrated Security=True";

        HttpPostedFileWrapper file = test.file; //No es necesario lo pongas en una variable, pero lo pongo para mostrar el tipo de dato

        if (file.ContentLength > 0)
        {

            int size = file.ContentLength;
            string fname = file.FileName;
            int position = fname.LastIndexOf("\");
            fname = fname.Substring(position + 1);

            string contentType = file.ContentType;
            byte[] fileData = new byte[size];
            file.InputStream.Read(fileData, 0, size);

            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "INSERT INTO Testsoru(Name, Wiw, Formato)" +
                  " VALUES(@Name,@wiw,@format,@Size,@FName,@Type)";

                using (SqlCommand cmd = new SqlCommand(query))
                {

                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Name", test.name);
                    cmd.Parameters.AddWithValue("@wiw", test.wiw);
                    cmd.Parameters.AddWithValue("@format", test.formato);
                    cmd.Parameters.AddWithValue("@Size", size);
                    cmd.Parameters.AddWithValue("@FName", fname);
                    cmd.Parameters.AddWithValue("@Type", contentType);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                    con.Close();
                }
            }
        }

        return View(test);
    }

The model, if needed:

public class testsoru
{
    public string name { get; set; }
    public string formato { get; set; }
    public string wiw { get; set; }
    public HttpPostedFileWrapper file { get; set; }
}
    
answered by 27.10.2017 в 22:32