我通过这种方法使用网络服务:
$.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/