我无法理解如何将上传的文件内容发送到我的ASPX服务器端。这适用于HTML-4实现,其中File API在客户端不可用,并且使用.NET v4.0。
这是我到目前为止所拥有的:
FileReceiver.aspx上的HTML:
<input type="button" id="uploadFile" value="Upload" />
<div class="hidden">
<form id="uploadFileForm">
<input type="file" id="browseForFiles" />
</form>
</div>
(客户端)JS:
$("#uploadFile").click(function () {
$("#browseForFiles").click();
});
$("#browseForFiles").change(function () {
$("#uploadFileForm").submit();
});
$("#uploadFileForm").submit(function (e) {
// prevent default action
e.preventDefault();
// send file to server
$.ajax({
url: "FileReceiver.aspx/ReceiveFile",
type: "post",
dataType: "multipart/form-data", // <---- is this right?
data: ???, // <-------------------------- what goes here?
success: function(data) {
// do something on success
}
});
});
(服务器端)FileReceiver.aspx.cs:
[WebMethod]
public static string ReceiveFile(??? receivedFile) // <-- what type goes here?
{
// do something and return status
}
请帮助填写两个&#34; ???&#34;在上面的代码中。提前谢谢!
答案 0 :(得分:0)
这应该有效
$("#uploadFileForm").submit(function (e) {
// prevent default action
e.preventDefault();
var formData = new FormData($('#uploadFileForm')[0]);
$.ajax({
url: "FileReceiver.aspx/ReceiveFile",
type: "POST",
// Form data
data: formData, // <-- see above to see where this comes from
dataType: "json", // <-- the dataType you're RETURNING, not sending
cache: false,
//Options to tell jQuery not to process data or worry about content-type.
contentType: false,
processData: false,
success: function(data) {
// do something on success
}
});
});
然后你的C#代码应该是这样的
[WebMethod]
public static string ReceiveFile(HttpPostedFileBase receivedFile)
{
// do something and return status
}