MVC4 C#-要将图像保存到文件夹并将url保存到数据库中吗

MVC4 C#-要将图像保存到文件夹并将url保存到数据库中吗,c#,database,image,asp.net-mvc-4,C#,Database,Image,Asp.net Mvc 4,我对MVC4编码相当陌生。以前在SharePoint中进行过编程 我遇到的问题是,我想将图像保存到特定文件夹(比如App_数据),并将图像的url保存到数据库中的字符串中。 如果有人能帮我解决这个问题就太好了 我现在得到的密码是 模型>ImageUpload.cs public class ImageUpload { public int ID { get; set; } public string Title { get; set; } public string

我对MVC4编码相当陌生。以前在SharePoint中进行过编程

我遇到的问题是,我想将图像保存到特定文件夹(比如App_数据),并将图像的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; }
}
查看>图像上传>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>
@{
ViewBag.Title=“Index”;
}
指数

@ActionLink(“新建”、“创建”)

@DisplayNameFor(model=>model.Title) @DisplayNameFor(model=>model.Url) 预览 @foreach(模型中的var项目){ @DisplayFor(modeleItem=>item.Title) @DisplayFor(modelItem=>item.Url) item.Url)“alt=“@Html.DisplayFor(modelItem=>item.Title)”> @ActionLink(“编辑”,“编辑”,新的{id=item.id})| @ActionLink(“详细信息”,“详细信息”,新的{id=item.id})| @ActionLink(“删除”,“删除”,新的{id=item.id}) }
查看>图像上载>创建.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")
}
@{
ViewBag.Title=“创建”;
}
创造
@使用(Html.BeginForm()){
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
图像上传
@使用(Html.BeginForm())
{
@LabelFor(Model=>Model.Title)
@EditorFor(Model=>Model.Title)
@Html.ValidationMessageFor(Model=>Model.Title)
@LabelFor(Model=>Model.Url)
@EditorFor(Model=>Model.Url)
}
}
@ActionLink(“返回列表”、“索引”)
@节脚本{
@Scripts.Render(“~/bundles/jqueryval”)
}

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

在控制器中:

[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>

形象
@Html.HiddenFor(model=>model.ImageUrl)
@Html.ValidationMessageFor(model=>model.Url)

将两种方法组合成一种方法逻辑,代码应如下所示:

[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");
    }

在控制器操作中,您需要执行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获取图像并调整其大小,那么您肯定应该采用第一种方法


来源:

我不会费心将图像保存到
App\u Data
文件夹中,就好像您正在将url存储到该文件夹中一样,它将无法通过web访问。当它似乎可以一次性完成全部工作时,为什么您有单独的创建和上载方法?将图像二进制存储在DB中是一个更好的选择。。
<img src="http://cdn.foo.com/myimage.jpg" alt="" />