首先,我现在已经尝试了每一页,但没有任何帮助。所以这看起来像所有其他公共汽车它不是
我只想要一个文件上传器,首先保存图像并将图像的ID作为字符串传回隐藏的输入字段,以便在提交表单时再次找到图像。 / p>
无论我做什么,我都无法阻止页面刷新,这会使输入字段消失:( 这是我的代码
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;
});
CONTROLLER
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);
}
答案 0 :(得分:0)
你的#file-uploader是否位于一个带有动作方法的表单中?
我会尝试关闭action属性,然后将该属性添加到ajax调用的success函数中的form元素。
答案 1 :(得分:0)
我刚刚禁用了“启用浏览器同步”,它正在运行。