使用onclick函数和ajax上传图像文件?

问题描述

我尝试使用onclick函数上传图像文件,并且可以使用ajax吗?我搜索有关如何上传图像的信息,但只有我可以看到是通过单击功能。但是我有一个原因,这就是为什么我使用onclick函数。控制器始终为空值

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

这是我的jquery和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");
        }
    });
}

我的控制器

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();
}

解决方法

尝试此代码:

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
  }
}

在服务器端:

[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);
        }