locked
Unable to send posted file in webmethod : Jquery Ajax RRS feed

  • Question

  • User1052662409 posted

    Hi All,

    Below is my ajax function

    $("#btn_Add_Diesel_Details").click(function () {
                    debugger;
    
                    var fileUpload = $('[id$=flDocs]').get(0);
                    var files = fileUpload.files;
                    var file = files[0]
                    var filename = files[0].name;
                    var UserName = $("#user_Name").val();
                    var UserLocation = $("#user_Location").val();
                    var Date = $("#diesel_Detail_Date").val();
                    var TrailersUnloading = $("#no_Of_Trailers_Unloading").val();
                    var TrailersLoading = $("#no_Of_Trailers_Loading").val();
                    var TotalNoOfTrailers = $("#total_No_of_Trailers").val();
                    var DieselInLtrs = $("#diesel_In_Ltrs").val();
                    var DieselInAmount = $("#diesel_In_Amount").val();
                    var CraneOperatiorName = $("#crane_Operatior_Name").val();
                    var BillFrontCopy = filename;
                    var BillBackCopy = $("#bill_Back_Copy").val();
                    var User_Id =<%= Session["user_id"].ToString() %>
    
                        $.ajax({
                            url: 'diesel_Log.asmx/AddDiesaldetail',
                            enctype: 'multipart/form-data',
                            method: 'post',
                            data: "{'UserName':'" + UserName + "', 'UserLocation':'" + UserLocation + "','Date':'" + Date + "', 'TrailersUnloading':'" + TrailersUnloading + "','TrailersLoading':'" + TrailersLoading + "' , 'TotalNoOfTrailers':'" + TotalNoOfTrailers + "' ,   'DieselInLtrs':'" + DieselInLtrs + "' ,'DieselInAmount':'" + DieselInAmount + "' ,'CraneOperatiorName':'" + CraneOperatiorName + "' , 'BillFrontCopy':'" + BillFrontCopy + "' , 'BillBackCopy':'" + BillBackCopy + "','User_Id':'" + User_Id + "','file':'" + file + "'}",
                            //data: '{Diesel: ' + JSON.stringify(Diesel_log) + '}',
                            contentType: false,
                            dataType: "json",
                            success: function () {
                                alert("Data Send Successfully")
                            },
                            error: function (err) {
                                console.log(err);
                            }
    
                        });
                    var Date = $("#diesel_Detail_Date").val("");
                    var TrailersUnloading = $("#no_Of_Trailers_Unloading").val("");
                    var TrailersLoading = $("#no_Of_Trailers_Loading").val("");
                    var TotalNoOfTrailers = $("#total_No_of_Trailers").val("");
                    var DieselInLtrs = $("#diesel_In_Ltrs").val("");
                    var DieselInAmount = $("#diesel_In_Amount").val("");
                    var CraneOperatiorName = $("#crane_Operatior_Name").val("");
                    var BillFrontCopy = $("#bill_Front_Copy").val("");
                    var BillBackCopy = $("#bill_Back_Copy").val("");
    
                    Approved_dieselReports();
    
    
    
    
                });

    It works fine If I do not upload a file. But

     [WebMethod(EnableSession = true)]
    
        public string AddDiesaldetail(string UserName, string UserLocation, string Date, string TrailersUnloading, string TrailersLoading, string TotalNoOfTrailers, string DieselInLtrs, string DieselInAmount, string CraneOperatiorName, string BillFrontCopy, string BillBackCopy, string User_Id, HttpPostedFile file)
        {
            string id = string.Empty;
            DataTable dt = new DataTable();
            DBHelper oDBHelper = new DBHelper();
            Hashtable param = new Hashtable();
    
            if (Context.Request.Files.Count > 0)
            {
    
                HttpFileCollection files = Context.Request.Files;
                
                    file = files[0];
    
                file.SaveAs(Server.MapPath("EmpDocs/" + file.FileName));
                string bucketname = "*******";
                string localpath = Server.MapPath("EmpDocs/" + file.FileName);
                string s3path = "diesel_bills/" + file.FileName;
                UploadFiles obj = new UploadFiles();
                bool uploaded;
    
                uploaded = obj.sendMyFileToS3Subforlder(bucketname, file.FileName, localpath, s3path);
                File.Delete(Server.MapPath("EmpDocs/" + file.FileName));
    
                param.Add("@Bill_Front_Copy", file.FileName);
            }
            else
            {
                param.Add("@Bill_Front_Copy", "");
    
            }
    
            // DateTime ndt = DateTime.ParseExact(Date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            param.Add("@User_Name", UserName);
            param.Add("@User_Location", UserLocation);
            param.Add("@No_of_Trailers_Unloading", TrailersUnloading);
            param.Add("@No_of_Trailers_Loading", TrailersLoading);
            param.Add("@Total_No_of_Trailers", TotalNoOfTrailers);
            param.Add("@Diesel_In_Ltrs", DieselInLtrs);
            param.Add("@Diesel_In_Amount", DieselInAmount);
            param.Add("@Crane_Operatior_Name", CraneOperatiorName);
           
            param.Add("@Bill_Back_Copy", BillBackCopy);
            param.Add("@user_Id", User_Id);
    
            param.Add("@type", "insert");
            int result = oDBHelper.Insert_Update_Delete("usp_Diesel_Log", param);
            return "AddDiesaldetail123";
        }


    when I try to upload a file it doesn't call the web method to insert parameters. Below is my web method. (When I try to add a new item in JSON :-'file':'" + file + "')

    and it works fine when I don't upload the file.

    Tuesday, June 30, 2020 8:34 AM

Answers

All replies

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 30, 2020 10:10 AM
  • User-474980206 posted

    To upload a file via jquery, you use a form post and the browsers FormData() object for the data.

    https://developer.mozilla.org/en-US/docs/Web/API/FormData

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 30, 2020 2:28 PM
  • User288213138 posted

    Hi demoninside9,

    demoninside9

    when I try to upload a file it doesn't call the web method to insert parameters. Below is my web method. (When I try to add a new item in JSON :-'file':'" + file + "')

    and it works fine when I don't upload the file.

    You can try to use th HTML5 FormData JavaScript object. here a demo for you as a reference.

    <input type="file" name="postedFile" />
        <input type="button" id="btnUpload" value="Upload" />
        <progress id="fileProgress" style="display: none"></progress>
        <hr />
        <span id="lblMessage" style="color: Green"></span>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $("body").on("click", "#btnUpload", function () {
                $.ajax({
                    url: 'Handler.ashx',
                    type: 'POST',
                    data: new FormData($('form')[0]),
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (file) {
                        $("#fileProgress").hide();
                        $("#lblMessage").html("<b>" + file.name + "</b> has been uploaded.");
                    },
                    xhr: function () {
                        var fileXhr = $.ajaxSettings.xhr();
                        if (fileXhr.upload) {
                            $("progress").show();
                            fileXhr.upload.addEventListener("progress", function (e) {
                                if (e.lengthComputable) {
                                    $("#fileProgress").attr({
                                        value: e.loaded,
                                        max: e.total
                                    });
                                }
                            }, false);
                        }
                        return fileXhr;
                    }
                });
            });
        </script>
    
    public void ProcessRequest(HttpContext context)
        {
            //Check if Request is to Upload the File.
            if (context.Request.Files.Count > 0)
            {
                //Fetch the Uploaded File.
                HttpPostedFile postedFile = context.Request.Files[0];
               
                //Set the Folder Path.
                string folderPath = context.Server.MapPath("~/Uploads/");
     
                //Set the File Name.
                string fileName = Path.GetFileName(postedFile.FileName);
               
                //Save the File in Folder.
                postedFile.SaveAs(folderPath + fileName);
     
                //Send File details in a JSON Response.
                string json = new JavaScriptSerializer().Serialize(
                    new
                    {
                        name = fileName
                    });
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.ContentType = "text/json";
                context.Response.Write(json);
                context.Response.End();
            }
        }
     
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    Hope this can help you.

    Best regards,

    Sam

    Wednesday, July 1, 2020 3:13 AM