Step 1. 新增Controller及Action
以下程式碼為驗證使用,沒有進行任何安全過濾,請不要使用。
Imports System.IO Namespace UpDownFileFromDBMvc Public Class FileUploadAndSessionTestController Inherits System.Web.Mvc.Controller ' ' GET: /FileUploadAndSessionTest/Upload Function Upload() Return View() End FunctionFunction Upload(upfile As HttpPostedFileBase ) If upfile IsNot Nothing andalso upfile.ContentLength > 0 Then Dim savePath As String = Path.Combine(Server.MapPath("~/Files/"), upfile.FileName) upfile.SaveAs(savePath) TempData("FileName") = upfile.FileName End If Return RedirectToAction("FileInfo") End Function Function FileInfo() ViewBag.FileName = TempData("FileName") Return View() End Function End Class End Namespace
以上參考該網友提供程式碼,我所撰寫的VB程式碼。
Step 2. 新增Upload與FileInfo的View
Upload.aspx
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Upload </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Upload</h2> <%Using Html.BeginForm("Upload", "FileUploadAndSessionTest", FormMethod.Post, New With {.enctype = "multipart/form-data"})%> <%: Html.ValidationSummary(True)%> File:<input id="upfile" name="upfile" type="file" value="" /> <br /> <input type="submit" value="Upload" /> <%End Using%> </asp:Content>
FileInfo.aspx
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> FileInfo </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>FileInfo</h2> Upload File Nale: <%: ViewBag.FileName %> </asp:Content>
以下為執行結果圖。
圖一:Upload File then Pass file name(點擊看大圖) |