2013-05-07 41 views
2

我很新的MVC4編碼。以前一直在SharePoint中編程。MVC4 C# - 想要保存圖像到一個文件夾,並保存在數據庫中的網址

我遇到的問題是,我想將圖像保存到特定的文件夾(比方說App_Data),並將圖像的網址保存到數據庫中的字符串中。 如果有人能幫助我解決這個問題,那將會很棒。

我現在得到的代碼是。

模型> 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") 
} 
+0

我不會理會的圖像保存到'App_Data'文件夾,如果你存儲的URL,它不會通過網絡進行訪問。 – 2013-05-07 08:09:31

+0

爲什麼你有獨立的創建和上傳方法,似乎它可以一次完成整個事情? – 2013-05-07 08:28:17

+0

在DB中存儲圖像二進制是一個更好的選擇.. – Paritosh 2013-07-26 06:08:21

回答

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

相關問題