2012-02-27 24 views
0

アップロードしたファイルのリンクをデータベースに保存します。 は、誰もがここで私に を助けてください は私がするFileUploadコントロールを使用しています しかし、私は、私はMVCに新しいです閲覧URL を保存することはできませんよと、私が試したものです:私は多くのミスがある知っているアップロードされたファイルのリンクを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> 

それ.. しかし、これを通過してください..私は本当に私の知る限り、なるように(フォルダが保護されてApp_Dataフォルダ内のファイルへの直接URLを取得することはできません知っているよう

答えて

0

それを理解していないです をたとえばデータベースファイルを保存することができます)。別のフォルダにアップロードする必要があります(例:~/Uploads)。次に、URLを作成してstring url = "http://yourwebsite.com/Uploads/" + filename;というように作成し、モデルに保存することができます。

関連する問題