Send file with ajax of jQuery to web service in C# (asmx)

前端 未结 3 774
北海茫月
北海茫月 2021-01-02 12:43

I\'m using web service with this method:

        $.ajax({
            type: \'POST\',
            url: \'page.asmx/method\',
            contentType: \'appli         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 13:15

    You need to serialize you data....

      var data = new FormData();
    
      var files = $("#YOURUPLOADCTRLID").get(0).files;
    
      // Add the uploaded image content to the form data collection
      if (files.length > 0) {
           data.append("UploadedFile", files[0]);
      }
    
      // Make Ajax request with the contentType = false, and procesDate = false
      var ajaxRequest = $.ajax({
           type: "POST",
           url: "/api/fileupload/uploadfile",
           contentType: false,
           processData: false,
           data: data
           });
    

    And inside the controller you can have something like

    if (HttpContext.Current.Request.Files.AllKeys.Any())
    {
       // Get the uploaded image from the Files collection
       var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
    
       if (httpPostedFile != null)
       {
       // Validate the uploaded image(optional)
    
       // Get the complete file path
           var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
    
        // Save the uploaded file to "UploadedFiles" folder
        httpPostedFile.SaveAs(fileSavePath);
    }
     }
    

    Hope it helps...

提交回复
热议问题