0

I try to upload image file using onclick function and ajax is it possible ? I search about on how to upload image but only i can see is via click function. but I have a reason for this that's why i used onclick function. controller is always null value

<div class="col-md-2">
    <div class="form-group">
        @Html.LabelFor(x => x.ImagePath, new { @class = "form-label" })
        <input type="file" name="file" id="files" />
    </div>
</div>

<div class="col-md-2">
    <div class="form-group">
        <button type="submit" id="btnUpload" class="btn btn-primary btn-sm" onclick="saveImage()"><i class="fas fa-save"></i> &nbsp;Submit Image</button>
    </div>
</div>

and this is my jquery and ajax

function saveImage() {
    var formData = new FormData();
    formData.append('file', $('#files')[0].files[0]);

    $.ajax({
        url: '@Url.Action("index", "payable")',
        type: 'POST',
        data: formData,
        traditional: true,
        success: function (data) {
            alert("success");
        }
    });
}

My controller

public ActionResult Index() 
{
    HttpPostedFileBase file = Request.Files[0];

    string fileName = Path.GetFileNameWithoutExtension(file.FileName);
    string extension = Path.GetExtension(file.FileName);
    fileName = fileName + extension;
    var ImagePath = "~/Image/" + fileName;
    fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
    file.SaveAs(fileName);

    return View();
}
3
  • Your Ajax call is sending the file by POST while that Index method is GET (the default). You need [HttpPost] attribute and please don't call it Index, choose proper name. Commented Aug 29, 2020 at 14:02
  • @derloopkat ill try to add [httppost] but still the same my file parameter is null. Commented Aug 29, 2020 at 14:10
  • in your ajax, set these to false: contentType: false, processData: false, Commented Aug 29, 2020 at 14:23

1 Answer 1

2

try this code:

var ufiles = $("#fileInput")[0].files;
if (ufiles.length > 0) {
  if (window.FormData !== undefined) {
    var fileData = new FormData();
    //handling multiple files or single file
    for (var x = 0; x < ufiles.length; x++) {
      fileData.append(ufiles[x].name, ufiles[x]);
    }
    $.ajax({
      type: "POST",
      url: "yourUrl",
      contentType: false,
      processData: false,
      data: fileData,
      success: function (result) {
        //do something with result
      },
    });
  } else {
    alert("This browser doesn't support HTML5 file uploads!"); //bootbox dependency
  }
}

And on server side:

[HttpPost]
        public JsonResult Index()
        {
            HttpPostedFileBase file = HttpContext.Request.Files[0];//this can be put under foreach for multiple files

            string fileName = Path.GetFileNameWithoutExtension(file.FileName);
            string extension = Path.GetExtension(file.FileName);
            fileName = fileName + extension;
            var ImagePath = "~/Image/" + fileName;
            fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
            file.SaveAs(fileName);
            //now cause we are hadnling ajax
            return Json(fileName,JsonRequestBehavior.AllowGet);
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.