2012-02-27 33 views
0

我想將上傳文件的鏈接存儲在我的數據庫中。 我使用FileUpload控件 但我不能夠存儲瀏覽網址 我是新來的MVC 請人幫我 這裏是我曾嘗試:要將上傳文件的鏈接存儲在mvc3數據庫中

//Inside Model 
public class Hobbies 
{ 
    public int Id { get; set; } 
    public string hobbiename { get; set; } 
    public string filelocation { get; set; } 
    public string hobbydetail { get; set; } 
} 

//inside Controller action method create 
[HttpPost] 
    public ActionResult Create(Hobbies hobbies,HttpPostedFileBase file) 
    { 
     var r = new List<Hobbies>(); 
     if (file != null && file.ContentLength > 0) 
     { 
      // extract only the fielname 
      var fileName = Path.GetFileName(file.FileName); 
      // store the file inside ~/App_Data/uploads folder 
      var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
      file.SaveAs(path); 
     } 

     if (ModelState.IsValid) 
     { 
      db.hobby.Add(hobbies); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(hobbies); 
    } 
//inside Create.cshtml 
@model MVCUpload4.Models.Hobbies 

@{ 
ViewBag.Title = "Create"; 
} 

<h2>Create</h2> 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"  type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

@using (Html.BeginForm()) { 
@Html.ValidationSummary(true) 
<fieldset> 
    <legend>Hobbies</legend> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.hobbiename) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.hobbiename) 
     @Html.ValidationMessageFor(model => model.hobbiename) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.filelocation) 
    <input type="file" name="file"/> 

    </div> 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.hobbydetail) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.hobbydetail) 
     @Html.ValidationMessageFor(model => model.hobbydetail) 
    </div> 

    <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 
} 

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

我知道有很多錯誤它.. 但請通過這個.. 我真的不理解它

回答

0

據我知道這是不可能得到直接的URL到一個文件中App_Data文件夾(文件夾保護,使得可以保存例如數據庫文件)。您需要將其上傳到其他文件夾(例如~/Uploads)。然後你可以像這樣構建URL:string url = "http://yourwebsite.com/Uploads/" + filename;並將它存儲在你的模型中。

相關問題