I am returning request failed but the save is working. What is wrong with this?

Natavia Finnie
Natavia Finnie used Ask the Experts™
on
I am trying to upload multiple files. Everything seems to be working just fine but my controller is saying that the request failed. What am I doing wrong?

$(document).ready(function () {
    $('#RequestDetailFiles').on('click', function () {
        var data = new FormData();

        var files = $("#DetailFileUpload").get(0).files;

        // Add the uploaded image content to the form data collection
        if (files.length > 0) {
            for (i = 0; i < files.length; i++) {
                data.append("UploadedImage_" + i, files[i]);
            }
        }

        $('#DetailAppended').empty();
        $('#RequestDetailUploaded').empty();
        $("#RequestDetailUploaded").append('<p>Uploaded Files</p>');
        $("#RequestDetailUploaded").append('<ul id="DetailAppended">');
        for (var i = 0; i < files.length; i++)
            $("#DetailAppended").append('<li>' + files[i].name + '</li>');

        //append other form data.
        var requestId = $("#RequestId").val();
        data.append("Type", "Request Details");
        data.append("TypeId", "1");
        data.append("RequestId", requestId);

        // Make Ajax request with the contentType = false, and procesDate = false
        var ajaxRequest = $.ajax({
            type: "POST",
            url: "/uploadfile/uploadfile",
            contentType: false,
            processData: false,
            data: data,
            success: function (data) {
                //data is your result from controller
                if (files.success) {
                }
            },
            error: function (xhr) {
                //alert('error');
            }
        });

        ajaxRequest.done(function (xhr, textStatus) {
            alert("success");
            // Do other operation
        });
    });
});

Open in new window


  [HttpPost]
        public ActionResult UploadFile()
        {
            RequestContext dbContext = new RequestContext();
            Attachment thisAttachment = new Attachment();

            var attachments = new List<Attachment>();

            if (HttpContext.Request.Files.AllKeys.Any())
            {
                for (var i = 0; i < HttpContext.Request.Files.Count; i++)
                {
                    var httpPostedFile = HttpContext.Request.Files["UploadedImage_" + i];

                    var typeId = HttpContext.Request.Form["TypeId"];
                    var type = HttpContext.Request.Form["Type"];
                    var requestId = HttpContext.Request.Form["RequestId"];

                    if (httpPostedFile != null)
                    {
                        //Get the complete file path
                        var fileSavePath = Path.Combine(HttpContext.Server.MapPath("~/Attachments"), httpPostedFile.FileName);

                        thisAttachment = new Attachment()
                        {
                            Filename = httpPostedFile.FileName,
                            Path = fileSavePath,
                            TypeId = Convert.ToInt32(typeId),
                            CreatedOn = DateTime.Today,
                            RequestId = int.Parse(requestId)
                        };

                        dbContext.Attachments.Add(thisAttachment);
                        dbContext.SaveChanges(); 

                        // Save the uploaded file to "UploadedFiles" folder
                        httpPostedFile.SaveAs(fileSavePath);
                    }
                }
            }            
           return View();
        }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
Hi Natavia,

Could you please tell me from which line it returns the error? Also have you tried putting debug point and see if it is coming from your controller? And what error code you are getting?

From the code snipped you have posted, both success and failure won't give any information to you. Error is commented out and success has no code in it.
if (files.success) {
                }
            },
            error: function (xhr) {
                //alert('error');
            }

Open in new window


And this additional code
        ajaxRequest.done(function (xhr, textStatus) {
            alert("success");
            // Do other operation
        });

Open in new window


I would check the value of textStatus before I provide the alert stating the operation was successful.

Regards,
Chinmay.
Senior Software Engineer
Top Expert 2009
Commented:
For AJAX calls, your controller method shall return JsonResult as follows:
return Json("Your OK message goes here", JsonRequestBehavior.AllowGet);

Open in new window

that replaces:
return View();

Open in new window

I saw this earlier but left it alone because @Chinmay and @Miguel are providing excellent assistance. Just saw it again as I was going through my first email purge of the morning and I realized that you're probably getting back a timeout error. As your code is currently written, this is going to happen when you start dealing with larger files and/or sets of smaller files that end up taking longer than your application's timeout threshold (whatever that may be). To get around this...

1. Change your controller method return type to System.Threading.Task<ActionResult> and use the async modifier.
2. Use the await modifier on anything in your method that is awaitable.
3. Unless you have a good reason not to, you should Dispose of anything that implements IDisposable, such as your DbContext (unless that ends up breaking things).

Those are a start for optimization. Also, you should consider abstracting all this away to a separate process. Why? Because all your users care about is that their files were successfully uploaded to the server. Everything else after that doesn't matter to them... and would ideally be handled by a custom Windows Service. That implementation is non-trivial and WAY outside the scope of your question, however.

Good Luck!
You need to see the response received from server. If it's an error then go throw the error message which will provide the inside detail of the cause.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial