查看代码
<input type="text" id="txtImageName"></input>
<input type="text" id="txtImageDescription"></input>
<input type="file" id="txtImageName"></input>
<input type="button" id="btnUpload" Value="Upload">
Jquery代码
<script>
$('#btnUpload').click(function () {
var file = $("#txtImageName").get(0).files;
$.ajax({
type: 'post',
url: "@Url.Action("HomeAddNew", "Admin")",
data:
{
ImageName: $('#txtImageNameoption').val(),
ImageDescription:$('#txtImageDescription').val(),
Image: file
},
success: function (data) {
alert('hai');
},
error: function (data) {
alert('error');
}
});
});
</script>
控制器代码
public ActionResult HomeAddNew(string ImageName, string ImageDescription, HttpPostedFileBase Image)
{
//in the above HttpPostedFilebase I'm getting the null value but, I don't want to use .fileupload method or formdata class in jquery.
return View();
}
解释:每当我在控制器方法中检查文件时,它都显示为null
。请给我一个完美的解决方案。这对我很有帮助。我的电子邮件地址是ganesh@concai.co.uk
答案 0 :(得分:0)
您无法使用ajax上传文件。如果您的浏览器要求从IE10
开始,那么您可以使用xhr
。
有关如何执行此操作的代码和信息HERE。
此外,还有一个名为FileAPI
的插件,您可以找到HERE
使用progress bar
function startUpload() {
var fileInput = document.getElementById("fileInput");
if (fileInput.files.length == 0) {
alert("Please choose a file");
return;
}
var progressBar = document.getElementById("progressBar");
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percentComplete = (e.loaded / e.total) * 100;
progressBar.value = percentComplete;
};
xhr.onload = function() {
if (xhr.status == 200) {
alert("Sucess! Upload completed");
} else {
alert("Error! Upload failed");
}
};
xhr.onerror = function() {
alert("Error! Upload failed. Can not connect to server.");
};
progressBar.value = 0;
xhr.open("POST", "ajax-upload", true);
xhr.setRequestHeader("Content-Type", fileInput.files[0].type);
xhr.send(fileInput.files[0]);
}