【发布时间】:2013-10-09 19:04:33
【问题描述】:
使用我在这里找到的有用信息:
How can I upload files asynchronously?
我能够使用以下 jQuery 将表单数据获取到服务器端(对上面的链接稍作修改):
$('#addFileInput').change(function () {
var file = this.files[0];
name = file.name;
size = file.size;
type = file.type;
//Your validation
});
$('.submitFile').click(function () {
var formData = new FormData($("#fileUploadForm"));
$.ajax({
url: '/AJAX Pages/Compute_File_Upload.cshtml', //Server script to process data
type: 'POST',
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function () {
$("#progressBar").css("visibility", "visible");
},
success: function (response) {
$(".editLabelTitle").text(response);
},
//error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e) {
if (e.lengthComputable) {
$('progress').attr({ value: e.loaded, max: e.total });
}
}
以下是所涉及的 HTML:
<div class=\"addFileBox\">
<div class=\"editPageSubTitle dragHandle\">
Add File
<button id=\"closeAddFileBox\">X</button>
</div>
<div class=\"innerAddFileDiv\">
<form id=\"fileUploadForm\" enctype=\"multipart/form-data\">
<input id=\"addFileInput\" name=\"addFileInput\" type=\"file\" />
</form>
<br/>
<progress id=\"progressBar\"></progress>
<br/>
<button class=\"submitFile\">Submit File</button>
</div>
</div>
Ajax 请求本身可以正常工作。当我不知道如何在服务器端代码上获取文件时,问题就出现了(通常我只会使用Request.Files["someFileId"]) 找到输入,但由于发送了所有 formData,这不是我熟悉的方式与。
C# 代码隐藏
@{
Layout = "";
if(IsAjax)
{
var file = Request.Files["addFileInput"];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/CMS Files/UtilityBilling"), fileName);
file.SaveAs(path);
}
}
考虑到我的场景和环境,访问给定文件的正确方法是什么?
【问题讨论】:
-
理论上,您访问它的方式与访问它的方式相同,就好像它是使用
-
@KevinB 这就是我的代码现在设置的方式,但我在
var fileName = Path.GetFileName(file.FileName);行收到“对象引用未设置为对象实例”错误。 -
@KevinB 我以前在常规形式的帖子中使用过
Request.Files。您确定它应该以相同的方式访问吗?我想知道... -
我不熟悉 asp/C#,我只知道使用 FormData 对象发送 ajax 请求,因为 POST 数据类型的数据应该模仿普通表单发布的数据。您是否包含了正确的 enctype,就像您需要在发布文件的普通表单元素上一样?
-
@KevinB 如果您的意思是将
enctype属性放在表单标签中,例如:<form enctype="multipart/form-data">那么是的,我就是这样做的。
标签: c# jquery ajax webmatrix asp.net-webpages