[英]Upload and View Files ASP.NET MVC 5
我有這個代碼:
[HttpPost]
public ActionResult Create(Knowledgebase KB, HttpPostedFileBase file)
{
var KBFilePath = "";
if (ModelState.IsValid)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(KB.KnowledgebaseTitle);
var path = Path.Combine(Server.MapPath("~/Resources/KBArticles"), fileName + ".pdf");
KBFilePath = path;
file.SaveAs(path);
}
KB.KnowledgebaseLink = KBFilePath;
db.Knowledgebases.Add(KB);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
else
{
return View();
}
鏈接是存儲在以C:/ C開頭的DB中的文件路徑
在另一個頁面上,我可以查看記錄的內容。 當我點擊其保存在C:/上的鏈接時,Chrome會顯示“無法加載本地資源”。 我保存到Resources文件夾中,該文件夾是我的ASP.NET應用程序目錄的一部分。 無論如何圍繞這個?
編輯該頁面由此視圖提供:
public ActionResult Suggestions(String Tag)
{
return View();
}
編輯2 - 我把更改放在我的視圖中:
@{
string tag = "<td><a href=" + "~/Content/Files/" + ">" + item.Title.Replace(" ", "") + ".pdf" + "</a>" + "</td>";
}
@Html.Raw(tag)
瀏覽器地址欄中請求的文件是
http://localhost:62165/Incident/~/Content/Files/
現在我收到HTTP錯誤404.0 Not Found錯誤
這是一個完整的示例,顯示如何上傳文件並通過鏈接將其下載。
創建一個空的MVC項目。 我使用MVC 4,但它應該與MVC 5一起使用。
控制器:
在HomeController
我們將有一個單一的動作Index
,它將顯示可供下載的文件列表和上傳新文件的選項。
行動Index
GET:
Index
視圖的模型。 行動Index
POST:
碼:
public class HomeController : Controller
{
public ActionResult Index()
{
var path = Server.MapPath("~/Content/Files/");
var dir = new DirectoryInfo(path);
var files = dir.EnumerateFiles().Select(f => f.Name);
return View(files);
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
var path = Path.Combine(Server.MapPath("~/Content/Files/"), file.FileName);
var data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
using (var sw = new FileStream(path, FileMode.Create))
{
sw.Write(data, 0, data.Length);
}
return RedirectToAction("Index");
}
}
視圖:
在視圖中,我們需要生成一個包含文件鏈接的列表。 這里我們需要處理包含空格的文件名,並用'%20'替換它們。
上傳文件的表單很簡單。 只是一個輸入標簽來獲取文件和一個按鈕來發送表單。
@model IEnumerable<string>
@{
ViewBag.Title = "Index";
}
<h2>Files</h2>
<ul>
@foreach (var fName in Model)
{
var name = fName;
var link = @Url.Content("~/Content/Files/") + name.Replace(" ", "%20");
<li>
<a href="@link">@name</a>
</li>
}
</ul>
<div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="File" name="file" id="file" value="Choose File"/>
<button type="submit">Upload</button>
}
</div>
結果應該是:
嘗試將文件保存在“內容”文件夾中。 您可以創建子文件夾Content / Files。 把文件放在那里。 然后生成如下鏈接:
<a href="~/Content/Files/file1.pdf">File1</a>
或者如果要直接下載,請使用下載屬性:
<a href="~/Content/Files/file1.pdf" download>File1</a>
。
大多數Web服務器都配置為拒絕對內容文件夾之外的內容的請求。 這可以在配置文件中修改,但如果您使用內容文件夾,則更容易(也更安全)。 這是基於我的經驗,如果有人認為我錯了,請讓我知道我的答案。 我總是很高興學到新的東西。
編輯1:如何建立a
動態標簽
在視圖中,您需要一個字符串變量link
保存要顯示的鏈接和另一個變量的文本path
來保存路徑(也許兩者都是從數據庫加載到控制器)。 然后你可以像這樣手動構建標簽:
@{
string tag = "<a href=" + path + ">" + link + "</a>";
}
@Html.Raw(tag)
編輯2:處理Url中的空格。
您需要使用Html.Content
來獲取正確的相對Url。
@{
string link = item.Title;
string path = Url.Content("~/Content/Files/") + link.Replace(" ", "%20") + ".pdf";
string tag = "<a href=" + path + ">" + link + "</a>";
}
@Html.Raw(tag)
首先是創建視圖<
<div class="form-group"> @Html.LabelFor(model => model.ImageData, new { @class = "control-label col-md-2" })
<div class="col-md-10"> <input name="Image" type="file" />
@Html.ValidationMessageFor(model => model.ImageData)
</div>
</div>
然后控制器創建操作
public ActionResult Create(ArtWork artwork, HttpPostedFileBase image) {
if (ModelState.IsValid) {
if (image != null) { //attach the uploaded image to the object before saving to Database
artwork.ImageMimeType = image.ContentLength;
artwork.ImageData = new byte[image.ContentLength];
image.InputStream.Read(artwork.ImageData, 0, image.ContentLength); //Save image to file
var filename = image.FileName;
var filePathOriginal = Server.MapPath("/Content/Uploads/Originals");
var filePathThumbnail = Server.MapPath("/Content/Uploads/Thumbnails");
string savedFileName = Path.Combine(filePathOriginal, filename);
image.SaveAs(savedFileName); //Read image back from file and create thumbnail from it
var imageFile = Path.Combine(Server.MapPath("~/Content/Uploads/Originals"), filename);
using (var srcImage = Image.FromFile(imageFile))
using (var newImage = new Bitmap(100, 100))
using (var graphics = Graphics.FromImage(newImage))
using (var stream = new MemoryStream()) {
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(srcImage, new Rectangle(0, 0, 100, 100));
newImage.Save(stream, ImageFormat.Png);
var thumbNew = File(stream.ToArray(), "image/png");
artwork.ArtworkThumbnail = thumbNew.FileContents;
}
}
//Save model object to database
db.ArtWorks.Add(artwork);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(artwork);
}
然后獲取Image或GetThumbnail方法
public FileContentResult GetThumbnailImage(int artworkId) {
ArtWork art = db.ArtWorks.FirstOrDefault(p => p.ArtWorkId == artworkId);
if (art != null) {
return File(art.ArtworkThumbnail, art.ImageMimeType.ToString());
} else {
return null;
}
}
這里是視圖中的顯示
<td> <img src="@Url.Action("GetThumbnailImage", "Artwork", new { Model.ArtWorkId })" alt="Artwork Image" /> </td>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.