asp.net上傳圖片,上傳圖片


 

想必很多人工作中經常需要實現上傳圖片的功能。

先引用此插件 http://files.cnblogs.com/files/hmYao/jquery-form.js。

前台代碼

<form data-ajax-success="AfterUpload" enctype="multipart/form-data" id="frm">
        <input type="file" name="fileBase" value=" " id="imgUpload" class="jiangli_1_w" />
        <input type="submit" id="btnSub" value="上傳圖片" /> <span class="flat_loe">上傳圖片寬度最大尺寸720px,高度無限制</span>
 </form>
 //上傳圖片
           $("#btnSub").click(function () {
                $("#frm").ajaxSubmit({
                    url: "/Slide/UploadImage",
                    type: "Post",
                    success: AfterUpload
                });
                return false;
            });

     function AfterUpload(msg) {
            if (msg != "0") {
                $("#imgPath").removeAttr("src").attr("src", msg);
            } else {
                swal({
                    title: "溫馨提示",
                    text: "圖片格式有誤"
                });
                $("#imgPath").val("");
                return false;
            }
        }

對應的后台代碼如下:

      /// <summary>
        /// 上傳圖片
        /// </summary>
        /// <param name="fileBase"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase fileBase)
        {
            string imgurl = string.Empty;
            string imgPath = System.IO.Path.GetFileName(fileBase.FileName);
            int index = imgPath.LastIndexOf('.');
            string suffix = imgPath.Substring(index).ToLower();
            if (suffix == ".jpg" || suffix == ".jpeg" || suffix == ".png" || suffix == ".gif" || suffix == ".bmp")
            {
                string pictureName = DateTime.Now.Ticks.ToString() + suffix; //圖片名稱
                string savePath = Server.MapPath("/Files/Images/SlideConfig/");//幻燈片文件夾
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                imgurl = "http://" + Request.Url.Authority + "//Files/Images/SlideConfig/" + pictureName;
                fileBase.SaveAs(savePath + pictureName);
            }
            else
            {
                imgurl = "0";
            }
            return Content(imgurl);
        }

有一點很重要,很多人都拿不到上傳的路徑值。注意參數的名稱 需要和 file標簽的name相同。

到此結束...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM