我想将上传文件的链接存储在我的数据库中。 我正在使用FileUpload Control 但我无法存储浏览的网址 我是mvc的新手 请有人帮帮我 这是我尝试过的:
//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 :(得分:0)
据我所知,无法获取App_Data
文件夹中文件的直接URL(该文件夹受到保护,因此可以保存例如数据库文件)。您需要将其上传到其他文件夹(例如~/Uploads
)。然后,您可以构建如下的URL:string url = "http://yourwebsite.com/Uploads/" + filename;
并将其存储在模型中。