【发布时间】:2018-05-02 21:43:45
【问题描述】:
嘿,我想上传图片并将该图片保存到一个文件夹中,并将该图片的名称保存到数据库,此外我还为其他表单字段使用模型绑定。这是此 HttpPostedFileBase 文件中的代码接收 null 我也在我的表单中使用 enctype = "multipart/form-data"。
public ActionResult UmrahPackage(PackagesModel model, , HttpPostedFileBase file)
{
try
{
if (model.ID == 0)
{
String fileName = "";
Pakage pkg = new Pakage();
pkg.Title = model.Title;
pkg.PackageDetail = model.PackageDetail;
pkg.Duration = model.Duration;
if (file != null)
{
fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName);
string physicalPath = Server.MapPath("~/Images/Uploads" + fileName);
// save image in folder
file.SaveAs(physicalPath);
}}
此外,我也在尝试这个,但我无法理解如何将图像保存在文件夹中,我的意思是 SaveAs -> 文件之前的对象实例
if (Request.Files.Count > 0 && String.IsNullOrEmpty(Request.Files[0].FileName) == false)
{
HttpPostedFileBase file;
fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(Request.Files[0].FileName);
string physicalPath = Server.MapPath("/uploads/profileimages/") + fileName;
file.SaveAs(physicalPath);
}
我的表单看起来像,
@using (Html.BeginForm("UmrahPackage", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
@Html.HiddenFor(model => model.ID)
<label>Title:</label>
@Html.TextBoxFor(model => model.Title)
<label>Upload Image</label>
<input type="file" id="imgInp">
<button type="submit" >Create</button>
}
请帮助我,谢谢。
【问题讨论】:
-
你的表单代码是什么样子的?
-
您可以看到我更新的视图代码。
标签: c# asp.net-mvc razor file-upload