C#工具:ASP.NET MVC单例模式(懒汉)实现文件上传
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.后台代码
// 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(); }