2

我对 MVC4 编码很陌生。之前一直在 SharePoint 中编程。

我遇到的问题是我想将图像保存到特定文件夹(比如说 App_Data),并将图像的 url 保存到数据库中的字符串中。如果有人可以帮助我解决这个问题,那就太好了。

我现在得到的代码是。

模型 > ImageUpload.cs

public class ImageUpload

{
    public int ID { get; set; }
    public string Title { get; set; } 
    public string Url { get; set; }
}

public class ImageUploadDBContext : DbContext
{
    public DbSet<ImageUpload> ImageUploads { get; set; }
}

控制器 > ImageUploadController.cs

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(ImageUpload imageupload)
    {
        if (ModelState.IsValid)
        {
            db.ImageUploads.Add(imageupload);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(imageupload);
    }

[HttpPost]
    public ActionResult Upload(HttpPostedFileBase[] files)
    {
        foreach (HttpPostedFileBase file in files)
        {
            string picture = Path.GetFileName(file.FileName);
            string path = Path.Combine(Server.MapPath("~/App_Data"), picture);
            string[] paths = path.Split('.');
            string time = DateTime.UtcNow.ToString();
            time = time.Replace(" ", "-");
            time = time.Replace(":", "-"); 
            file.SaveAs(paths[0] + "-" + time + ".jpg");
        }
        ViewBag.Message = "File(s) uploaded successfully";
        return RedirectToAction("Index");
    }

查看 > ImageUpload > Index.cshtml

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Url)
        </th>
        <th>
            Preview
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Url)
            </td>
            <td>
                <img border="0" src="@Html.DisplayFor(modelItem => item.Url)" alt="@Html.DisplayFor(modelItem => item.Title)">
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
                @Html.ActionLink("Details", "Details", new { id=item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ID })
            </td>
        </tr>    
    }
</table>

查看 > ImageUpload > Create.cshtml

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>ImageUpload</legend>

            @using (Html.BeginForm())
            {
                    <div class="editor-label">
                        <b>@Html.LabelFor(Model => Model.Title)</b>
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(Model => Model.Title)
                        @Html.ValidationMessageFor(Model => Model.Title)
                    </div>
                    <div class="editor-label">
                        <b>@Html.LabelFor(Model => Model.Url)</b>
                    </div>
                    <div>
                        @Html.EditorFor(Model => Model.Url)
                        <input type="file" name="files" value="" multiple="multiple"/>
                    </div>
                    <div>
                        <input type="submit" value="Submit" />
                    </div>
            }


    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
4

3 回答 3

1

对于文件上传,您可以使用此代码。图像保存到文件夹和文件名存储到数据库:

在控制器中:

[HttpPost]
public ActionResult Create(EventModel eventmodel, HttpPostedFileBase file)
{ 
   if (ModelState.IsValid)
   {
      var filename = Path.GetFileName(file.FileName);
      var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
      file.SaveAs(path);
      tyre.Url = filename;

      _db.EventModels.AddObject(eventmodel);
      _db.SaveChanges();
      return RedirectToAction("Index");
   }
   return View(eventmodel);
}

并查看:

<div>
   Image
   <input type="file" name="file" id="file" />
   @Html.HiddenFor( model => model.ImageUrl)
   @Html.ValidationMessageFor( model => model.Url )
</div>
于 2013-07-26T06:08:20.933 回答
0

在您的控制器操作中,您需要执行 HTTP 请求以从远程服务器获取图像:

public ActionResult Thumb(int id)
{
    using (var client = new WebClient())
    {
        byte[] image = client.DownloadData("http://cdn.foo.com/myimage.jpg");
        return File(image, "image/jpg");
    }
}

接着:

<img src="@Url.Action("Thumb")" alt="" />

显然现在图像被下载了两次。一次从 CDN 进入控制器,一次从客户端进入。这完全违背了此控制器操作的目的,您可以直接从 CDN 引用图像:

<img src="http://cdn.foo.com/myimage.jpg" alt="" />

这显然假设客户端可以访问 CDN。

当然,如果您的控制器操作不仅仅是从 CDN 获取图像并将其流式传输到客户端,例如从 CDN 获取图像并调整其大小,那么您绝对应该采用第一种方法。

来源:stackoverflow

于 2014-09-27T05:35:41.730 回答
0

将两种方法合二为一的方法逻辑,代码应该是这样的:

[HttpPost]
[ValidateAntiForgeryToken]
    public ActionResult Upload(HttpPostedFileBase[] files)
    {
        // try to save the file
        foreach (HttpPostedFileBase file in files)
        {
            string picture = Path.GetFileName(file.FileName);
            string path = Path.Combine(Server.MapPath("~/App_Data"), picture);
            string[] paths = path.Split('.');
            string time = DateTime.UtcNow.ToString();
            time = time.Replace(" ", "-");
            time = time.Replace(":", "-"); 
            file.SaveAs(paths[0] + "-" + time + ".jpg");
        }

        // try to save the new file name to db now.
        try
        {
            db.ImageUploads.Add(paths[0] + time + ".jpg");
            db.SaveChanges();
        }
        catch(Exception ex)
        {
             ..........
        }

        ViewBag.Message = "File(s) uploaded successfully";
        return RedirectToAction("Index");
    }
于 2014-03-07T17:08:09.030 回答