Avatar of Natavia Finnie
Natavia Finnie
Flag 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

C#jQuery

Avatar of undefined
Last Comment
Omer Rasheed

8/22/2022 - Mon
Chinmay Patel

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
Miguel Oz

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Kelvin McDaniel

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!
Omer Rasheed

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.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck