使用jQuery Ajax将文件发送到C#中的Web服务(asmx) [英] Send file with ajax of jQuery to web service in C# (asmx)
本文介绍了使用jQuery Ajax将文件发送到C#中的Web服务(asmx)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过这种方法使用Web服务:
I'm using web service with this method:
$.ajax({
type: 'POST',
url: 'page.asmx/method',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '{}'
});
发送json字符串,它可以工作,但是如果我尝试使用FormData追加输入的内容并将其传递到数据值中,我将得到500响应.我该怎么办?
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?
推荐答案
您需要序列化数据....
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);
}
}
希望有帮助...
这篇关于使用jQuery Ajax将文件发送到C#中的Web服务(asmx)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文