4

I have a form with Image and another fileds, I want to send data with image in controller.

  <form id="first-form"  method="post" enctype="multipart/form-data">
   <div class="row">
      <div class="col-md-9">
       <div class="row">
        <div class="col-sm-6 form-group">
         @Html.Label(@RegisterResource.Name, new { @class = "control-label" })
         <div class="field-input">
         @Html.TextBox("Name", null, new { placeholder = @RegisterResource.Name, autofocus = "autofocus", @class = "input-text" })
         @Html.ValidationMessage("Name", null, new { @class = "text-danger" })
        </div>
       </div>
      <div class="col-sm-6 form-group">
        @Html.Label(@RegisterResource.Family, new { @class = "control-label" })
         <div class="field-input">
         @Html.TextBox("Family", null, new { placeholder = @RegisterResource.Family, @class = "input-text" })
         @Html.ValidationMessage("Family", null, new { @class = "text-danger" })
        </div>
       </div>
       </div>
       <div class="row">
        <div class="col-sm-6 form-group">
          @Html.Label(@RegisterResource.CellPhone, new { @class = "control-label" })
           <div class="field-input">
           @Html.TextBox("CellPhone", null, new { placeholder = @RegisterResource.CellPhone, maxlength = 11, @class = "input-text", onkeydown = "return ValidateNumber(event);" })
            @Html.ValidationMessage("CellPhone", null, new { @class = "text-danger" })
           </div>
          </div>
          <div class="col-sm-6 form-group">
            @Html.Label(@ContractorResource.City, new { @class = "control-label" })
          <div class="field-input">
            @Html.DropDownList("CityId", (SelectList)ViewBag.City, new { placeholder = @ContractorResource.City, @class = "input-text" })
            @Html.ValidationMessage("CityId", null, new { @class = "text-danger" })
          </div>
         </div>
        </div>
        </div>
        <div class="col-md-3 text-center">
          <img id="image_upload_preview" class="img-circle" src="~/Content/Images/contractor-avator.png" />
          <br />
          <input type="file" id="inputFile" style="max-width: 200px" />
          <label for="inputFile" class="btn-2">انتخاب فایل تصویر</label>
         </div>
         </div>
         <div class="order-complate text-center">
         <button type="submit" class="awe-btn awe-btn-1 awe-btn-medium" id="user-register-btn" data-loading-text="<i class='fa fa-spinner fa-spin '></i> @PageResource.ConfirmCode">@PageResource.Continues</button>
         </div>
    </form>

and in jquery

function readURL(input) {
 if (input.files && input.files[0]) {
   var reader = new FileReader();
   reader.onload = function(e) {
     $('#image_upload_preview').attr('src', e.target.result);
 }

 reader.readAsDataURL(input.files[0]);
 fileImage = input.files[0];
     }
}

$("#inputFile").change(function() {
  readURL(this);
});

submitHandler: function() {
  $("#user-register-btn").button('loading');
  var data = $('#first-form').serialize();
  var formData = new FormData();  
  formdata.append("img", fileImage );             
  $.post("/Contractor/SendConfirmCode",
   data,
    function(result) {
     } 
    else {
     }
   },
  "json");

But in controller Request.Files is Empty.

ar.gorgin
  • 4,765
  • 12
  • 61
  • 100

2 Answers2

5

Thanks to @jishan for his comprehensive answer;

If I were you, I would prefer a view model for posting the form data, however,

according to your View:

    $('#user-register-btn').click(function (e) {

        e.preventDefault();

        $("#user-register-btn").button('loading');


        //var data = $('#first-form').serialize();
        var data = {
            Name: $('#Name').val(),
            Family: $('#Family').val(),
            CityId: $('#CityId').val(),
            CellPhone: $('#CellPhone').val()
        };

        var formData = new FormData();

        formData.append("data", JSON.stringify(data));

        var totalFiles = document.getElementById('inputFile').files.length;
        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById('inputFile').files[i];
            formData.append("httpPostedFileBase", file);
        }
        $.ajax({
            type: "POST",
             url: '/Contractor/SendConfirmCode',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (response) {
                if (response != null) {
                    console.log(response);      
                  $('#image_upload_preview').attr('src', response[0].FilePath);                 
                }
                else {
                    alert('No Response...!');
                }
            },
            error: function (error) {
                alert("error");
            }
        });
        
    });

and in your controller:

    [HttpPost]
    public ActionResult SendConfirmCode(HttpPostedFileBase[] httpPostedFileBase, string data)
    {
        if(Request.Files.Count > 0)
        {
            // as you wish
        }


        ModelForm formData = JsonConvert.DeserializeObject<ModelForm>(data);
        // save formData to DB or ...

        return View();
    }

and, the model class that matches the form data :

public class ModelForm
{
    public string Name { get; set; }
    public string Family { get; set; }
    public string CityId { get; set; }
    public string CellPhone { get; set; }
}
Deepak paramesh
  • 495
  • 1
  • 8
  • 19
A. Nadjar
  • 2,440
  • 2
  • 19
  • 20
1

You need change script for uploading image.

In this example when you select the file using your file control "inputFile" mention in view then jquery file change event occurs.

View code for single file

 <div class="col-md-3 text-center">
      <img id="image_upload_preview" class="img-circle" src="~/Content/Images/contractor-avator.png" />
      <br />
      <input type="file" id="inputFile" style="max-width: 200px" />
      <label for="inputFile" class="btn-2">انتخاب فایل تصویر</label>
     </div>

View code for selection multiple file

<div class="col-md-3 text-center">
          <img id="image_upload_preview" class="img-circle" src="~/Content/Images/contractor-avator.png" />
          <br />
          <input multiple="" type="file" id="inputFile" style="max-width: 200px" />
          <label for="inputFile" class="btn-2">انتخاب فایل تصویر</label>
         </div>

Jquery file change code in this example if you want to select multiple file or single file

/*FILE UPLOAD HERE*/
    var alldata = []
    $('#inputFile').change(function () {
        try {
            var formData = new FormData();
            var totalFiles = document.getElementById('inputFile').files.length;
            for (var i = 0; i < totalFiles; i++) {
                var file = document.getElementById('inputFile').files[i];
                formData.append("oHttpPostedFileBase", file);
            }
            $.ajax({
                type: "POST",
                url: '/Contractor/SendConfirmCode',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    if (response != null) {
                        console.log(response);      
                      $('#image_upload_preview').attr('src', response[0].FilePath);                 
                    }
                    else {
                        alert('No Response...!');
                    }
                },
                error: function (error) {
                    alert("error");
                }
            });
        } catch (e) {
            alert("File Upload Error" + e.message);
        }
    });

Add this code in controller file with this class

#region FileUpload handling
        /*File Upload*/
        [HttpPost]
        public ActionResult BaseAutoFileUpload(HttpPostedFileBase[] oHttpPostedFileBase)
        {
            try
            {            
                List<FileUploadClass> lstUploadFile = new List<FileUploadClass>();          
                string yourfilepathfolder = "~/Uploads/Junk/";
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    FileUploadClass oFileUploadClass = new FileUploadClass();
                    var file = Request.Files[i];
                    var fileName = Path.GetFileName(file.FileName);
                    fileName = Guid.NewGuid().ToString() + "_" + fileName;
                    var path = Path.Combine(Server.MapPath(yourfilepathfolder), fileName);
                    file.SaveAs(path);
                    oFileUploadClass.FileName = fileName.Substring(37);
                    oFileUploadClass.FileNameForDelete = fileName;
                    oFileUploadClass.FilePath = path;
                    lstUploadFile.Add(oFileUploadClass);
                }
                return Json(lstUploadFile);
            }
            catch (Exception ex)
            {               
                return Json(null);
            }
        }
        public class FileUploadClass
        {
            public string FileName { get; set; }
            public string FilePath { get; set; }
            public string FileNameForDelete { get; set; }
        }
        #endregion

Note: when you select file your file automatically saves on server given specific path in "yourfilepathfolder ".

if you have single file selection and you won't show file which file you have selected

just add this line in code

$('#image_upload_preview').attr('src', response[0].FilePath);

I'm added this line already for you please check.

check-in console

jishan siddique
  • 1,848
  • 2
  • 12
  • 23