微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用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);
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。