简体   繁体   中英

Pass UploadFile content as byte[] or object from jquery ajax function and upload via webmethod

I have an html page which contains a form with file upload input.

I need to pass all the fields in jquery ajax function to an aspx page containing a WebMethod and in this method I should upload the image to the website file system and not as bytes in the database.

Is this doable using jquery ajax with webmethod in c#

If you want to save the file to the Website file system than yes this is doable. I ran into a same scenario of uploading the files usinga webmethod and saw this question. I solved the problem so though of sharing my solution. Hope it will help someone.

Below is the code in which we create a FormData object and append our files to it and then pass this FormData object to the WebMethod through Jquery Ajax.

var Upload = function () {
            var fileInputCtrl = $('<input id="File_OpenInputCtrl"  type="file" style="position: fixed; top: -100em" multiple/>');
fileInputCtrl.off('change').on('change', function (evt) {
    var files = evt.target.files;
    var fd = new FormData();
    for (var f = 0; f < files.length; f++) {
        var file = files[f];

        fd.append(file.name, file);

    }

    // Upload the formdata
    $.ajax({
        url: "Webservice.asmx/UploadFiles",
        type: "POST",
        data: fd,
        contentType: false,
        processData: false,
        success: function (result) {
            alert(result);
            $('#File_OpenInputCtrl').remove();
        },
        error: function (err) {
            alert(err.statusText);
            $('#File_OpenInputCtrl').remove();
        }
    });
});
    fileInputCtrl.click();          
  }

The WebMethod

public string UploadFiles()
{
    //this function handles the upload of gallery images and magazine file 
    var Request = HttpContext.Current.Request;
    System.Web.HttpFileCollection Files = Request.Files;
    try
    {
        for (int i = 0; i < Files.Count; i++)
        {
            System.Web.HttpPostedFile File = Files[i];
            File.SaveAs(HttpContext.Current.Server.MapPath("~/Uploads/" + File.FileName));
        }
        return "Files Saved Successfully!";
    }
    catch (Exception ex)
    {
        return ex.Message;
    }


}

Hope it Helps.

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