首先,我現在嘗試了每一頁,但沒有任何幫助。所以這看起來像所有其他總線它不是防止Ajax/Json在成功後刷新頁面
我只是想要一個文件上傳器,其中圖像的保存第一次,並將圖像的ID作爲字符串傳回隱藏的輸入字段,所以我可以再次找到圖像表格已提交。
無論我做什麼我不能阻止頁面清爽,這使得輸入域消失:( 這裏是我的代碼
HTML
<label for="file-uploader" class="custom-file-upload">
<i class="fa fa-cloud-upload fa-5x"></i><br /> Custom Upload
</label>
<input style="display: none" id="file-uploader" name="file" multiple="" type="file" />
<div id="input-wrapper">
Here comes all input fields
</div>
AJAX/JSON
$("#file-uploader").change(function() {
var formData = new FormData();
var totalFiles = document.getElementById("file-uploader").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("file-uploader").files[i];
formData.append("file-uploader", file);
}
$.ajax({
type: "POST",
url: '@Url.Action("Fileuploader", "Admin")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data, e) {
$('#input-wrapper').append($('<input>').attr('type', 'hidden').attr('name', 'imagesId').attr('value', data.Id));
},
error: function(error) {
alert("error");
}
});
return false;
});
控制器
public JsonResult Fileuploader(int? pictureId)
{
db = new ApplicationDbContext();
var name = "";
if (pictureId != null)
{
var findImage = db.Imageses.Find(pictureId);
if (findImage == null) return Json(new { result = "Error" }, JsonRequestBehavior.AllowGet);
var filename = findImage.Url.Substring(10);
var path = Server.MapPath("~/Uploads/" + filename);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
db.Imageses.Remove(findImage);
db.SaveChanges();
}
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
name = Guid.NewGuid().ToString();
var fileformat = Path.GetExtension(file.FileName);
var filename = name + fileformat;
var path = Path.Combine(Server.MapPath("~/Uploads/"), filename);
file.SaveAs(path);
}
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var img = new Images()
{
Filename = file.FileName,
DateCreated = DateTime.Now,
Url = "~/Uploads/" + name
};
db.Imageses.Add(img);
db.SaveChanges();
}
}
return Json(new { result = "Sucess", Id=name }, JsonRequestBehavior.AllowGet);
}
我會推薦下載提琴手,看看你要求和接收 – Craig
我從來沒有嘗試,在這方面,提琴手。但所有數據都是正確的。因爲我的觀點是它只是爲了弄清爲什麼在ajax.succes之後仍然令人耳目一新。但我會立即嘗試提琴手:) –