我正在尝试使用jQuery Ajax上传和预览图像。但是,只要我仅选择图像文件,它就会重新加载页面。我在这里注意到的一件事是,如果我选择图像文件以外的文件,则不会重新加载页面。我已经在线检查了解决方案,并添加了为此建议的所有可能解决方案,即<input
type="email"
id="email"
name="email"
class="form-control"
placeholder="Enter Email"
<%= !email ? '' : "value="+email %>
/>
和contentType: false
,但仍无法按预期运行
HTML代码如下
event.preventDefault();
jQuery代码如下
<form id="createCategory">
<label>Name</label>
<input name="Name" />
<br />
<label>Description</label>
<input name="Description" />
<br />
<label>Image</label>
<input id="inpImageURL" name="ImageURL" type="hidden" />
<input id="inpImageUpload" name="Image" type="file"/>
<div class="thumb">
<img id="imgUploadImage" src="#" alt="your image" />
</div>
<br />
<button type="submit">Save</button>
</form>
ASP.Net MVC代码在下面
$("#inpImageUpload").change(function (event) {
debugger;
event.preventDefault();
var element = this;
var formData = new FormData();
var totalFiles = element.files.length;
for (var i = 0; i < totalFiles; i++) {
var file = element.files[i];
formData.append("Photo", file);
}
$.ajax({
type: 'POST',
url: '/Shared/UploadImage',
dataType: 'json',
data: formData,
processData: false,
contentType: false
})
.done(function (response) {
debugger;
alert('ajax was called success');
//console.log(response);
//if (response.Success) {
// //$("#imgUploadImage").attr("src", response.inpImageURL);
// //$("#inpImageURL").val(response.inpImageURL);
// alert('ajax was called success');
//}
})
.fail(function (XMLHttpRequest, txtStatus, errorThrown) {
alert("Failure AJAX Call");
});
});