一、上傳單張圖片
前端
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> @using (Html.BeginForm("addFile", "First", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" name="myFile" /> <input type="submit" /> } </div> </body> </html>
后台
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace 上傳圖片並把圖片保存在本地.Controllers { public class FirstController : Controller { public static string toImagePath = @"D:\"; // GET: First public ActionResult Index() { return View(); } [HttpPost] public ActionResult addFile() { try { HttpPostedFileBase file = Request.Files["myFile"]; string FileName = DateTime.Now.ToString("yyyyMMddhhmmss"); if (file.ContentType == "image/jpeg" || file.ContentType == "image/png") { if (int.Parse(file.ContentLength.ToString()) > ((1024 * 1024) * 5)) { //圖片大小不能大於5M; return Redirect("/First/Index"); } else { //圖片存儲路徑 file.SaveAs(toImagePath + FileName + ".jpg"); } } return Redirect("/First/Index"); } catch (Exception) { throw; } } } }
二、上傳多張圖片
前端
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> @using (Html.BeginForm("addFile", "First", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" multiple="multiple" name="myFile" /> <input type="submit" /> } </div> </body> </html>
后台
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace 上傳圖片並保存在本地.Controllers { public class FirstController : Controller { public static string toImagePath = @"D:\"; // GET: First public ActionResult Index() { return View(); } [HttpPost] public ActionResult addFile(IEnumerable<HttpPostedFileBase> myFile) { try { foreach (var file in myFile) { if (file != null && file.ContentLength > 0) { if (file.ContentType == "image/jpeg" || file.ContentType == "image/png") { if (int.Parse(file.ContentLength.ToString()) > (1024 * 1024) * 5) { //圖片大小不能大於5M; continue; } else { string FileName = DateTime.Now.ToString("yyyyMMddhhmmss"); //圖片存儲路徑 file.SaveAs(toImagePath + FileName + ".jpg"); } } } } return Redirect("/First/Index"); } catch (Exception) { throw; } } } }
檢查是否要創建上傳文件夾
private bool CreateFolderIfNeeded(string path) { bool result = true; if (!Directory.Exists(path)) { try {
Directory.CreateDirectory(path); return result; } catch (Exception) { result = false; } } return result; }
如何把圖片存儲到當前項目某個文件夾
string urlPath = Server.MapPath(toImagePath);// 讀取到當前虛擬目錄的根目錄
后續會陸續更新其他資料,喜歡請關注哦!