jojacafe
8/26/2016 - 11:04 AM

File upload input

File upload input

$('#logo').on('change', function (e) {
    var files = e.target.files;

    if (files.length > 0) {
        if (window.FormData !== undefined) {
            var data = new FormData();
            for (var x = 0; x < files.length; x++) {
                data.append("file" + x, files[x]);
            }

            $.ajax({
                type: "POST",
                url: '/Admin/Agency/UploadLogo',
                contentType: false,
                processData: false,
                data: data,
                success: function (result) {
                    console.log(result);
                },
                error: function (xhr, status, p3, p4) {
                    var err = "Error " + " " + status + " " + p3 + " " + p4;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).Message;
                    console.log(err);
                }
            });
        } else {
            alert("This browser doesn't support HTML5 file uploads!");
        }
    }
});
public JsonResult UploadLogo()
  {
      foreach (string file in Request.Files)
      {
          var fileContent = Request.Files[file];
          if (fileContent != null && fileContent.ContentLength > 0)
          {
              // get a stream
              var stream = fileContent.InputStream;
              // and optionally write the file to disk
              var fileName = Path.GetFileName(file) + ".png";
              var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
              using (var fileStream = System.IO.File.Create(path))
              {
                  stream.CopyTo(fileStream);
              }
          }
      }

      return Json(new { message = "OK" });
  }