我正在通过以下方法使用Web服务:
$.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 });
在控制器内部,您可以拥有类似
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); } }
希望能帮助到你…