ASP.NET MVC 点击创建按钮后图片无法上传至Blob Storage该如何解决?
问题根源
- 你违反了HTML规范,在Create的外层表单里嵌套了专门用于上传的内层表单,嵌套表单在HTML中不会生效,点击外层Create按钮提交时,内层表单里的文件选择控件的内容不会被提交到后台Create接口
- 现有的Create控制器方法既没有接收上传文件的参数,也没有调用图片上传的逻辑,就算文件正常提交也不会处理上传到Blob存储的流程
- 单独的Upload接口没有和当前的新建公告流程串联,就算调用成功也无法把上传得到的图片地址关联到你正在创建的公告数据里
解决方案
第一步:修改Create.cshtml视图
删除嵌套的Upload表单,把文件选择控件直接放到外层的Create表单内,修改后的表单核心代码如下:
@using (Html.BeginForm("Create", "Ad", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>AdViewModel</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <!-- 原有Title、Description、Location的表单控件保持不变 --> <div class="form-group"> @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Location, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Location, "", new { @class = "text-danger" }) </div> </div> <!-- 直接保留文件上传控件,删掉之前嵌套的Upload表单 --> <div class="form-group"> <label class="control-label col-md-2" for="Photo">Photo</label> <div class="col-md-10"> <input type="file" name="photo" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div>
第二步:修改Create控制器方法
给Create方法添加上传文件参数,在验证通过后先调用图片上传逻辑,再把得到的图片地址关联到新建的公告数据中,修改后的代码如下:
[HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create(AdViewModel model, HttpPostedFileBase photo) { if (ModelState.IsValid) { string imageUrl = null; // 判断是否上传了文件 if (photo != null && photo.ContentLength > 0) { // 调用已验证可用的上传方法 imageUrl = await imageService.UploadImageAsync(photo); } // 调整你的CreateAd方法,增加参数接收图片地址,存入对应的公告字段 CreateAd(model.Title, model.Description, model.Location, imageUrl); return RedirectToAction("ViewAds"); } return View(model); }
可选调整
如果你的业务不需要单独的Upload接口,可直接删除该接口,避免冗余代码。
内容的提问来源于stack exchange,提问作者salcudean
相关产品推荐
相关产品推荐

