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

2020-03-02 02:43发布

I'm using web service with this method:

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

Sending json string, and it works, but if I try to append with FormData the content of input and passing it in data value I have 500 response. What have I to do?

3条回答
你好瞎i
2楼-- · 2020-03-02 03:22
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)
 {
 }
查看更多
够拽才男人
3楼-- · 2020-03-02 03:23

You can send form object like : new FormData($(this)[0]) which send both input values and file object to the ajax call.

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
});
查看更多
够拽才男人
4楼-- · 2020-03-02 03:38

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...

查看更多
登录 后发表回答