我正在使用ASP.NET MVC,我想将表单数据传递给我的操作,但我注意到传递后我的操作中变量file
的值为null
public void ImgUpload(HttpPostedFileBase file)
{
bool isSavedSuccessfully = true;
String fName = "";
try
{
foreach (String filename in Request.Files)
{
file = Request.Files[filename];
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));
bool isExists = Directory.Exists(originalDirectory.ToString());
if (!isExists)
Directory.CreateDirectory(originalDirectory.ToString());
var path = string.Format("{0}\\{1}", originalDirectory.ToString(), file.FileName);
file.SaveAs(path);
}
}
}
catch (Exception e)
{
isSavedSuccessfully = false;
}
}
表格还有这两个标签:
<div class="form-group">
<label class="control-label" for="file">Filename:</label>
<div class="col-md-10">
<input type="file" name="file" id="file" />
</div>
</div>
<div class="col-md-10 col-md-offset-2">
<input id="submit" type="submit" value="Create" class="btn btn-default" />
</div>
这是功能:
<script>
$('#submit').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
var formDataa = new FormData(this.form);
$.ajax({
url: "/ImageUploader/ImgUpload",
type: "POST",
data: JSON.stringify(formDataa),
processData : false ,
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
</script>
实际上我正在尝试将文件上传到服务器,我认为我的问题是如何或者什么是处理发布数据的正确类型。