Link to home
Start Free TrialLog in
Avatar of Natavia Finnie
Natavia FinnieFlag for United States of America

asked on

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

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

Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

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.
ASKER CERTIFIED SOLUTION
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.