1.SingletonConfigRead幫助類安全
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApplication2.Models { public class SingletonConfigRead { public static readonly string Config = ""; //封閉無參構造函數,防止外部實例化調用 private SingletonConfigRead() { } //建立一個對象爲屬性 private static SingletonConfigRead single; /// <summary> /// 外部經過調用該方法獲得對象(線程安全的懶漢單利模式) /// </summary> /// <returns></returns> public static SingletonConfigRead GetInstns() { if (single == null) { lock (Config) { single = new SingletonConfigRead(); } } return single; } public string UploadFile(HttpPostedFileBase txtFile) { if (txtFile != null) { string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Content\\", txtFile.FileName); txtFile.SaveAs(path); using (FileStream fs = new FileStream(path, FileMode.Open)) { StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default); return sr.ReadToEnd(); } } return null; } } }
2.前臺代碼函數
<div> @using (Html.BeginForm("Index", "File", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.TextBox("txtFile", "", new { @type = "file" }) <input id="Submit1" type="submit" value="上傳" /> <input id="Submit1" type="submit" value="讀取文件" /> <br /> @:上傳文件是:@ViewBag.fileName @:文件內容是:@ViewBag.fileContent } </div>
3.後臺代碼spa
// GET: File public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(HttpPostedFileBase txtFile) { if (txtFile != null) { SingletonConfigRead s = SingletonConfigRead.GetInstns(); ViewBag.fileContent = s.UploadFile(txtFile); ViewBag.fileName = txtFile.FileName; } return View(); }