用jQuery的ajax发送文件到c#的web服务(asmx)

本文关键字:服务 web asmx 文件 ajax jQuery | 更新日期: 2023-09-27 18:02:36

我使用web服务与这个方法:

        $.ajax({
            type: 'POST',
            url: 'page.asmx/method',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{}'
        });

发送json字符串,它的工作,但如果我尝试用FormData添加输入的内容,并在数据值中传递它,我有500响应。我该怎么办呢?

用jQuery的ajax发送文件到c#的web服务(asmx)

您需要序列化您的数据....

  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
       });

在控制器内部你可以输入像

这样的内容
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);
}
 }

您可以发送表单对象,如:new FormData($(this)[0]),它发送输入值和文件对象给ajax调用。

var formData = new FormData($(this)[0]);
$.ajax({
    type: 'POST',
    url: 'page.asmx/method',
    data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
});
Send Client side value server side through jquery and ajax call.
Click On butto send value client side to server side
<script>
$(document).ready(function () {
$("#additembtn").click(function () {
            jQuery.ajax({
                url: '/TelePhone/Edit',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: {
                    Name: $('#txtUsername').val(),
                    Address: $('#txtAddress').val(),
                },
                error: function (request, status, error) {
                },
                sucess: function (data, status, request) {  
                }
            })
        });
});
</script>
// Web Servics Telephone.asmx
[HttpPost]
 public ActionResult Edit(string data)
 {
 }