【发布时间】:2019-04-01 20:36:21
【问题描述】:
如何在编辑表单时在图像视图中显示上传的图像,然后使用输入类型文件将该图像发送到控制器。
我正在尝试如下,但 HttpPostedFileBase 总是返回空值。
我的查看代码是
@using (Ajax.BeginForm("AddUpdateCategory", "Categories", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", OnComplete = "", OnSuccess = "", OnBegin = "", OnFailure = " }, new { @enctype = "multipart/form-data", id = "CategoryForm", novalidate = "novalidate" }))
{
<div class="file-upload ">
<button class="file-upload-btn" type="button" onclick="$('.file-upload-input').trigger( 'click' )">Add Image</button>
<div class="image-upload-wrap">
<input class="file-upload-input" type='file' name="file" onchange="readURL(this);" accept="image/*" />
<div class="drag-text">
<span> Drag and drop a file or select add Image</span>
</div>
</div>
<div class="file-upload-content">
<img class="file-upload-image" src="@Model.Base64String" alt="your image" />
@Html.HiddenFor(x=>x.FileName)
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove <span class="image-title">@Model.FileName</span></button>
</div>
</div>
</div>
}
下面是我的控制器代码。
public ActionResult AddUpdateCategory(Category objCategory, HttpPostedFileBase file, FormCollection fc)
{
using (HttpClient client = GetHttpClient())
{
try
{
if (file != null)
{
var filename = Path.GetFileName(file.FileName);
string extension = Path.GetExtension(file.FileName);
var fileid = Guid.NewGuid().ToString().Replace("-", "") + extension;
var path = Path.Combine(Server.MapPath("~/Uploads/Category/"), fileid);
file.SaveAs(path);
objCategory.ImageURL = fileid;
}
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error while uploading the files.");
}
}
return Json(new { ModelState }, JsonRequestBehavior.AllowGet);
}
【问题讨论】:
-
如果不知道您的表单代码,将很难为您提供帮助。也许您的文件输入的名称不是
file?请更新您的问题并提供更多详细信息。 -
我已经更新了我的帖子,请立即查看。
标签: javascript jquery asp.net-mvc