简体   繁体   中英

Dynamic file upload not working

I'm trying to upload any amount of files using JQuery and C# MVC. When I create the form data and post it, the Request.Files object is null.

The returned message is 'Please make sure you have uploaded all necessary documents.'

How can I pass the dynamically created input files to c# side?

Here is the HTML

<div style="text-align:center; display:block; width:100%; margin-bottom:20px" id="regPDFUpload"></div>

I then append file upload elements using the following code:

//create file uploaders
                        var i = response.pdfPageCount;
                        for (j = 0; j < i; j++) {
                            var _file = '<label style="float:left; width:100px; padding-top:15px;" for="filePDFUpload' + j + '">Page ' + (j + 1) + '</label><input type="file" style="width:70%; display: block; float:left; margin-bottom:7px;" id="filePDFUpload' + j + '" name="filePDFUpload' + j + '" />';
                            _file += '<div style="clear:left"></div>';
                            $('#regPDFUpload').append(_file);
                        }

Here is the JQuery where files are being added to formData

var i = $('#regdoc-page-count').val();

        var formData = new FormData();

        //add files to form data
        for (j = 0; j < i; j++) {

            formData.append('filePDFUpload' + j, 'filePDFUpload' + j);
        }

        formData.append("customerGUID", $('#Customer-Guid').val());
        formData.append("tempAccountNumber", $('#Temp-Account-Number').val());

        $.ajax({
            cache: false,
            url: 'uploadRegDoc',
            data: formData,
            type: 'POST',
            contentType: false,
            processData: false,
            success: regUpoadSignedRegistrationSucess,
            complete: resetWait,
            error: regFailure
        });

Here is the C# code

 [ValidateInput(false)]
        [HttpPost]
        public ActionResult UploadRegDoc(FormCollection form)
        {
            if (Request.Files.Count > 0)
            {
                //create customers folder in content/customer-doc
                string filepath = "";

                filepath = Server.MapPath("~/content/customer-docs/" + form["customerGUID"] + "/signed/");
                if (!System.IO.Directory.Exists(filepath))
                {
                    System.IO.Directory.CreateDirectory(filepath);
                }

                try
                {
                    //  Get all files from Request object  
                    HttpFileCollectionBase files = Request.Files;
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFileBase file = files[i];
                        string fname;

                        // Checking for Internet Explorer  
                        if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                        {
                            string[] testfiles = file.FileName.Split(new char[] { '\\' });
                            fname = testfiles[testfiles.Length - 1];
                        }
                        else
                        {
                            fname = file.FileName;
                        }

                        fname = Path.Combine(filepath, fname);
                        file.SaveAs(fname);
                    }

                    //redirect to 
                    return Json(new
                    {
                        success = true,
                        message = "redirect",
                        resultId = (int)UserRegistrationType.AdminApproval,
                    });

                }
                catch (Exception ex)
                {
                    //registration complete.
                    return Json(new
                    {
                        success = false,
                        message = "An error occured uploading your files. " + ex.Message,
                    });
                }
            }
            else
            {
                //registration complete.
                return Json(new
                {
                    success = true,
                    message = "Please make sure you have uploaded all necessary documents.",
                });
            }
        }

Big thank you to adeneo for commenting the answer above. Will create an official answer to make this as answered.

It was the JQuery code that appends the files to formData object. It needed to append the files from the file upload element.

Updated JQuery Code:

   for (j = 0; j < i; j++) {

            formData.append('filePDFUpload' + j, $('#filePDFUpload' + j).get(0).files[0]);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM