【发布时间】:2018-11-10 19:17:11
【问题描述】:
好的,所以我一直在搜索这点代码,几乎所有东西都可以工作。我可以上传图像并将其保存到创建的文件夹中。我也可以保存传递给数据库的其他值。我现在的问题是我想将文件路径保存到数据库,这样我就可以调用它来在另一页上显示图像。由于某种原因,它只会保存正在上传的图像名称而不是路径。
当我调试它并查看所有内容时,当我添加手表时
file.SaveAs(pathLoc);
表达式已被评估,没有值 void
这是我一直在使用的代码
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ImageInfo info, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
var pic = Path.GetFileName(file.FileName);
var pathLoc = Path.Combine(Server.MapPath("~/Uploads/") + pic);
file.SaveAs(pathLoc);
info.ImagePath = file.FileName;
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(info);
}
查看
<h2>Create</h2>
@using (Html.BeginForm("Create", "ImageInfoes", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="form-horizontal">
<h4>ImageInfo</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ImageName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ImageName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ImageName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ImageSize, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ImageSize, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ImageSize, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ImagePath, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input id="ImagePath" title="Upload a product image" type="file" name="file" />
</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>
型号
public partial class ImageInfo
{
public byte id { get; set; }
public string ImageName { get; set; }
public Nullable<long> ImageSize { get; set; }
public string ImagePath { get; set; }
}
任何事情都会有帮助。
【问题讨论】:
-
info.ImagePath = file.FileName; => FileName 只会给你文件...名称。
-
设置
pathLoc而不是file.Filename? -
当我将它从 file.FileName 更改为 pathLoc 时,db.SaveChanges();抛出和错误。
-
info.ImagePath = file.FileName;仅分配文件名 - 如果您想要路径,它需要是info.ImagePath = pathLoc;。你得到什么错误?最好的猜测是您在该字段上有一个最大长度并且超出了它。 -
请注意 Expression 已被评估并且没有值 void 消息只是告诉您
.SaveAs()方法没有返回值(它的签名是@987654330 @)
标签: c# html asp.net-mvc-4