[英]Uploading a file to an ASPX server-side page
我無法理解如何將上傳的文件的內容發送到我的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
}
請幫忙填寫兩個“ ???” 在上面的代碼中。 提前致謝!
這應該工作
$("#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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.