ASP.NET MVC上传图片前后台内容
生活随笔
收集整理的這篇文章主要介紹了
ASP.NET MVC上传图片前后台内容
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
//樣式采用bootstrap樣式?
//前端form表單代碼
//著重聲明:form表單必須是post方式,
//表單中enctype="multipart/form-data"的意思,是設(shè)置表單的MIME編碼。
//默認(rèn)情況,這個(gè)編碼格式是application/x-www-form-urlencoded,不能用于文件上傳;只有使用了multipart/form-data,才能完整的傳遞文件數(shù)據(jù),進(jìn)行下面的操作.
<h2>添加圖片:</h2> <form action="/Home/SaveInfo" method="post" enctype="multipart/form-data"><p><label for="file">選擇圖片:</label><input type="file" name="files" class="form-control" id="file"/></p><p><input type="submit" value="保存" class="btn btn-info" /></p> </form>//后臺(tái)asp.net MVC函數(shù)代碼?
/// <summary>/// 添加圖片/// </summary>/// <param name="files"></param>/// <returns></returns>[HttpPost]public ActionResult SaveInfo(HttpPostedFileBase files){if (files==null) {//判斷是否空提交Response.Write("<script>alert('請(qǐng)?zhí)峤籮pg/png圖片');");return RedirectToAction("Index");}string fileName = files.FileName;//文件名//獲取文件名的后綴,并轉(zhuǎn)為小寫(xiě)string extension = Path.GetExtension(fileName).ToLower();if (extension.Equals("jpg")|| extension.Equals("png")) {Response.Write("<script>alert('請(qǐng)?zhí)峤籮pg/png圖片');");return RedirectToAction("Index");}string name = System.Guid.NewGuid().ToString("N");//32位隨機(jī)數(shù)字作為新文件名string serverPath = Server.MapPath("/images/");//服務(wù)器圖片存儲(chǔ)位置string saveUrl = serverPath + name + extension;//文件存儲(chǔ)路徑+新文件名+后綴files.SaveAs(saveUrl);//保存圖片return RedirectToAction("Index");}?
總結(jié)
以上是生活随笔為你收集整理的ASP.NET MVC上传图片前后台内容的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 利用超链接<a>标签的【href】与【o
- 下一篇: ASP.NET Core微服务(一)——