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

标签 c# jquery ajax web-services file

我通过这种方法使用网络服务:

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

发送 json 字符串,它有效,但如果我尝试用 FormData 附加输入内容并将其传递到数据值中,我会得到 500 响应。我该怎么办?

最佳答案

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

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

在 Controller 内部你可以有类似的东西

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

希望对你有帮助

关于c# - 使用 jQuery 的 ajax 将文件发送到 C# 中的 Web 服务 (asmx),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31399883/

相关文章:

javascript - Codeigniter Jquery Ajax,无法将数据从 Controller 访问回html表单

javascript - AJAX 调用问题

javascript - 表单不提交回调

c# - 如何使用 string.Contains(string, System.StringComparison) 修复错误 CA1307?

javascript - 将鼠标光标设置在文本 block 的末尾

javascript - MediaElement 播放器 "success"回调未被执行,如果使用 Flash 回退,则 "ended"事件可能不会触发

jQuery 选择长度 - 无法获得准确的计数

c# - 不可为 Null 的字符串初始化为 Null

c# - 如何使用 Spring.Net 设置 NHibernate 以使用无状态 session ?

c# - Linq GroupJoin 与 Linq All in Select 的效率对比