使用ajax of jQuery将文件发送到C#(asmx)中的Web服务

Lau*_*nti 8 c# ajax jquery web-services file

我正在使用这种方法的Web服务:

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

发送json字符串,它工作,但如果我尝试使用FormData附加输入的内容并将其传递给数据值我有500响应.我该怎么办?

Jig*_*dya 8

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

  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
       });
Run Code Online (Sandbox Code Playgroud)

在控制器内你可以有类似的东西

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);
}
 }
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你...