Upload a file with ajax post in asp.net mvc

265
May 06, 2017, at 10:21 PM

I want to upload a file as sending an email if user choose a file. Here is my code;

  function SendCollectiveMail() {

        var despatchTypeId = $("#DespatchTypeId").val();
        var despatchGroupId = $("#DespatchGroupId").val();
        var despatchBalanceId = $("#BalanceOptionId").val();
        if (despatchBalanceId === "")
            despatchBalanceId = 0;
        var blokId = $("#BlockId").val();
        if (blokId === "")
            blokId = 0;

        var startDate = $("#StartDate").val();
        var endDate = $("#EndDate").val();
        var subject = $("#Subject").val();
        var aciklama = $("#Detail").val();
        var uploads = "";
        var formData = new FormData();
        var totalFiles = document.getElementById("FileUpload").files.length;
        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById("FileUpload").files[i];
            formData.append("FileUpload", file);
        }
        if (totalFiles > 0) {
            alert('Dosya sunucuya yüklendi.' + formData);
            $.ajax({
                type: "POST",
                url: '/Upload/UploadFile',
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    uploads = response.result;
                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("SendCollectiveMail", "CollectiveMail")',
                        dataType: "json",
                        data: JSON.stringify({ "_despatchTypeId": despatchTypeId, "_despatchGroupId": despatchGroupId, "_despatchBalanceOptionId": despatchBalanceId, "_blokId": blokId, "_firstDate": startDate, "_lastDate": endDate, "subject": subject, "aciklama": aciklama, "uploads": uploads }),
                        contentType: "application/json",
                        success: function (result) {
                            alert(result.Message);
                        }
                    });
                }, error: function (xhr, textStatus, errorThrown) {
                    console.log(xhr.statusText);
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
        } else {
            $.ajax({
                type: "POST",
                url: '@Url.Action("SendCollectiveMail", "CollectiveMail")',
                dataType: "json",
                data: JSON.stringify({ "_despatchTypeId": despatchTypeId, "_despatchGroupId": despatchGroupId, "_despatchBalanceOptionId": despatchBalanceId, "_blokId": blokId, "_firstDate": startDate, "_lastDate": endDate, "subject": subject, "aciklama": aciklama, "uploads": uploads }),
                contentType: "application/json",
                success: function (result) {
                    alert('Sunucu Mesajı: Mail gönderimi başarısız.');
                }
            });
        }


    }

And here is my controller code:

 public class UploadController : Controller
    {
        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFile()
        {
            try
            {
                string uploadedAddresses = "";
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var file = Request.Files[i];
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/TempUploads/"), fileName);
                    file.SaveAs(path);
                    uploadedAddresses += path + ",";
                }
                return Json(new { result = uploadedAddresses });
            }
            catch (Exception exc)
            {
                DataHelper dataHelper = new DataHelper();
                using (var con = dataHelper.CustomerConnection())
                {
                    con.Open();
                    var insertQuery = @"INSERT INTO [dbo].[Exception]
                                           ([Message])
                                     VALUES
                                           (" + exc.Message + ")";
                    con.Query(insertQuery);
                }
                throw;
            }

        }
    }

When I upload a file and call SendCollectiveMail function, I have get Not Found error on my ajax post. Where is my mistake ?

READ ALSO
in_array not working correctly with plus sign

in_array not working correctly with plus sign

I am using the in_array to compare values and see if they exist in the array

130
reading file line by line and adding lines to array

reading file line by line and adding lines to array

I want to read a file line by line in JavaEach line is added as an item to an array

293
Map as a method parameter

Map as a method parameter

I have data that is stored in the following way:

253