简体   繁体   中英

how to get the posted file sent by Ajax in the server-side Page method

I have been working on this whole day. I do not want to use any fancy plugin. My problem is basically this: In asp.net c#, the user can create an instance of an class (let's say student) and each instance has a file (image). I am using AJAX, and the code works fine. When user presses create button, I want to also send the posted file to the Page method, which can can save the file, while adding the record to the db. However, I am not able to get the posted file as FileInfo in Page method but as string. Is there a way to make this work?

function addBadge() {
            var badgeName = $('#txtBadgeName').val();
            var badgeDesc = $('#txtBadgeDesc').val();
            var badgeImage = $('#file_BadgeImage').get().files[0];
            $.ajax({
                type: "POST",
                url: "/Instructor/ManageBadges.aspx/CreateBadge",
                data: "{badgeName:'" + badgeName + "', \
                        badgeImage:'" + badgeImage + "',\
                        badgeDescription:'" + badgeDesc + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    .....
                    }
                }
            });

        }


[WebMethod]
    public static string CreateBadge(string badgeImage, string badgeName, string badgeDescription)
    {
        //HERE HOW CAN USE badgeImage ??
        //HOW CAN I CONVERT IT TO FileInfo and save ?

        Guid badgeId = Guid.NewGuid();
        BadgeInfo newbadge = new BadgeInfo();
        newbadge.BadgeId = badgeId;
        newbadge.BadgeName = badgeName;
        newbadge.BadgeDescription = badgeDescription;

    }

First, i would try setting the content type to:

 contentType:'multipart/form-data'

Then i would read this article about the support for AJAX and file upload.

jQuery Ajax File Upload

It appears that only recently it has started being supported. I know for a fact that when you post a regular form without ajax, it must have the enctype 'multipart/form-data in order to send the file.

I honestly am not familiar with file manipulation on ASP C# side of things but, i know you have some issues before you get to that side.

For those who need an ajax asp.net solution (submitting a form with a file) without using a fancy file upload plugin:

I strongly refer to a recent solution here: File Upload using jQuery AJAX in ASP.NET Web API

The indicated solution uses a controller which handles the fileupload, and the fileupload function of controller is invoked from the ajax. Let's say you have one ajax method for saving the form input to the database. After this ajax is done with success, in the success event, you need to write another piece of ajax code to perform the file upload which is defined in the controller class, as seen below:

 [HttpPost]
        public KeyValuePair<bool, string> UploadFile()
        {
            try
            {
                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    // Get the uploaded image from the Files collection
                    var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];

                    if (httpPostedFile != null)
                    {
                        // Validate the uploaded image(optional)

                        // Get the complete file path
                        var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Images/UploadedFiles"), httpPostedFile.FileName);

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

                        return new KeyValuePair<bool, string>(true, "File uploaded successfully.");
                    }

                    return new KeyValuePair<bool, string>(true, "Could not get the uploaded file.");
                }

                return new KeyValuePair<bool, string>(true, "No file found to upload.");
            }
            catch (Exception ex)
            {
                return new KeyValuePair<bool, string>(false, "An error occurred while uploading the file. Error Message: " + ex.Message);
            }
        }

Please refer to the post for the details.

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