我正在开发一个ASP.NET MVC 4应用程序,有很多视图,用户可以使用Ajax上传我保存在服务器上的文件。
我的查看页面是,
<div class="row">
<br />
<div class="col-md-4" >
@Html.TextBoxFor(m => m.fileUpload, new { @class = "form-control", style = "height:33px;", type = "file", accept = "image/*,application/pdf" }).DisableIf(() => Model.IsReadOnly == true)
</div>
@if (Model.Status != Intranet.Common.Constants.Status.View)
{
<div class="form-group">
<button id="btnSubmitUpload" name="Command" value="Save"
class="btn btn-default">
Upload
</button>
</div>
}
</div>
<script type="text/javascript">
var model = @Html.Raw(Json.Encode(Model))
$(document).ready(function () {
$("#btnSubmitUpload").click(function (event) {
$("#divLoading").hide();
event.preventDefault();
getTempUpload(event);
});
});
function getTempUpload(event)
{
var formData = new FormData($('fileUpload')[0]);
$.ajax
({
type: 'POST',
async: false,
url: RootUrl + "DocumentUpload/fnUpload",
data: { fileNamearg: formData },
cache: false,
datatype: "Json",
success: function (data) {
if (data != "") {
alert(data);
}
},
error: function (error) {
alert('Error' + error.responseText);
}
});
}
</script>
在我的模型中,
[FileTypes("pdf,jpg,jpeg,gif,tif,tiff,png")]
[DisplayName("File Upload")]
public virtual HttpPostedFileBase fileUpload { get; set; }
public string DocExtesnsion { get; set; }
public string DocPath { get; set; }
...
...
而Ajax方法是,
public JsonResult fnUpload(HttpPostedFileBase fileNamearg, FormCollection frmcoll)
{
TrnMstDocUploadModel model=new TrnMstDocUploadModel();
String resultMsg = string.Empty;
model.fileUpload = fileNamearg;
if (model.FileNameArg != null)
{
if (Convert.ToString(ConfigurationManager.AppSettings["UploadFileSizeValidation"]).ToUpper() == "YES")
{
if ((fileNamearg.ContentLength / 1024) / 1024 > Convert.ToInt32(ConfigurationManager.AppSettings["UploadFileSize"].ToString()))
{
resultMsg = "Maximum File Size Exceeded " + ConfigurationManager.AppSettings["UploadFileSize"].ToString() + " MB.";
}
if (string.IsNullOrEmpty(resultMsg))
{
TempSave("", model, out resultMsg);
return Json(resultMsg,JsonRequestBehavior.AllowGet);
}
}
}
return Json("", JsonRequestBehavior.AllowGet);
}
fnUpload方法工作正常,但问题是fileNamearg参数为null。当我使用表单操作和HttpPost方法尝试它时,它正在工作。但我想用Ajax来做。那么如何将HttpPostedFileBase参数传递给Ajax方法?请任何人帮忙