ASP.NET MVC上传图片前后台内容
生活随笔
收集整理的這篇文章主要介紹了
ASP.NET MVC上传图片前后台内容
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//樣式采用bootstrap樣式?
//前端form表單代碼
//著重聲明:form表單必須是post方式,
//表單中enctype="multipart/form-data"的意思,是設置表單的MIME編碼。
//默認情況,這個編碼格式是application/x-www-form-urlencoded,不能用于文件上傳;只有使用了multipart/form-data,才能完整的傳遞文件數據,進行下面的操作.
<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>//后臺asp.net MVC函數代碼?
/// <summary>/// 添加圖片/// </summary>/// <param name="files"></param>/// <returns></returns>[HttpPost]public ActionResult SaveInfo(HttpPostedFileBase files){if (files==null) {//判斷是否空提交Response.Write("<script>alert('請提交jpg/png圖片');");return RedirectToAction("Index");}string fileName = files.FileName;//文件名//獲取文件名的后綴,并轉為小寫string extension = Path.GetExtension(fileName).ToLower();if (extension.Equals("jpg")|| extension.Equals("png")) {Response.Write("<script>alert('請提交jpg/png圖片');");return RedirectToAction("Index");}string name = System.Guid.NewGuid().ToString("N");//32位隨機數字作為新文件名string serverPath = Server.MapPath("/images/");//服務器圖片存儲位置string saveUrl = serverPath + name + extension;//文件存儲路徑+新文件名+后綴files.SaveAs(saveUrl);//保存圖片return RedirectToAction("Index");}?
總結
以上是生活随笔為你收集整理的ASP.NET MVC上传图片前后台内容的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用超链接<a>标签的【href】与【o
- 下一篇: C#字符串截取,查找某字符下标