基於WebUploader的圖片上傳

風靈使發表於2018-09-11

UploadController.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication.Controllers
{
    /// <summary>
    /// 基於WebUploader外掛的圖片上傳例項
    /// </summary>
    public class UploadController : Controller
    {
        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 直接上傳
        /// </summary>
        /// <returns></returns>
        public ActionResult Upload()
        {
            return View();
        }

        /// <summary>
        /// 簡單上傳
        /// </summary>
        /// <returns></returns>
        public ActionResult SimpleUpload()
        {
            return View();
        }

        /// <summary>
        /// 模態框上傳
        /// </summary>
        /// <returns></returns>
        public ActionResult ModalUpload()
        {
            return View();
        }

        /// <summary>
        /// 上傳檔案方法
        /// </summary>
        /// <param name="form">表單引數</param>
        /// <param name="file">檔案</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadImg(FormCollection form, HttpPostedFileBase file)
        {
            try
            {
                string filePathName = string.Empty;
                string localPath = string.Empty;
                string imagePath = string.Empty;


                imagePath = "/Upload/Images/User/";
                localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload/Images/");

                if (Request.Files.Count == 0)
                {
                    throw new Exception("請選擇上傳檔案!");
                    //return Json(new JsonResultModel(-1,"請選擇上傳檔案",null));
                }

                string ex = Path.GetExtension(file.FileName);

                filePathName = Guid.NewGuid().ToString("N") + ex;
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                file.SaveAs(Path.Combine(localPath, filePathName));

                // string imgAddress = Request.Url.GetLeftPart(UriPartial.Authority) + imagePath + filePathName;
                string imgAddress = imagePath + filePathName;
                return Json(new
                {
                    Status = 200,
                    Message = "上傳圖片成功!",
                    Data = imgAddress
                });
            }
            catch (Exception)
            {
                //扔出異常
                throw;
            }

        }

    }
}

Upload.cshtml

@{
    ViewBag.Title = "WebUploader上傳例項";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<!--單獨模組-->
<!--上傳圖片-->
<div id="wrapper">
    <div id="container">
        <div id="uploader">
            <div class="queueList">
                <div id="dndArea" class="placeholder">
                    <div id="filePicker"></div>
                    <p>或將照片拖到這裡,並支援截圖貼上功能</p>
                </div>
            </div>
            <div class="statusBar" style="display:none;">
                <div class="progress">
                    <span class="text">0%</span>
                    <span class="percentage"></span>
                </div><div class="info"></div>
                <div class="btns">
                    <div id="filePicker2"></div>
                    <div class="uploadBtn">開始上傳</div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    $(function () {
        var callback = function (response) {
            if (response.Status == 200) {
                new PNotify({ title: "成功!", text: response.Message, type: 'success' });// 此處使用了Pnotify 外掛== alert
            } else {
                new PNotify({ title: "失敗!", text: response.Message, type: 'error' });
            }
        }

        _init_upload(callback);//初始化上傳外掛

    });
</script>

SimpleUpload.cshtml

@{
    ViewBag.Title = "WebUploader上傳例項";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<!--簡單模組-->
<div class="container form-horizontal">
    <div class="row form-group">
        <label class="control-label  col-lg-3 col-md-3">圖片地址</label>
        <div class="col-lg-5 col-md-6">
            <input class="form-control" name="askImage" id="askImage" disabled="disabled" style="max-width:100%;" />
        </div>
        <div id="uploadImg">上傳圖片</div>
        @*<button type="button" class="btn btn-primary">上傳圖片</button>*@
    </div>
    <div id="fileList" class="uploader-list  wu-example"></div>
</div>
<script>
    $(function () {
        //Test
        _init_simpleUpload();//初始化上傳方法
    })
</script>

ModalUpload.cshtml


@{
    ViewBag.Title = "ModalUpload";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<!--模態框 單獨模組-->
<div id="imgModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" style="width: 900px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title">上傳圖片</h4>
            </div>
            <div class="modal-body model-scroll" style="max-height: 500px;">
                <!--上傳圖片start-->
                <div id="wrapper">
                    <div id="container">
                        <div id="uploader">
                            <div class="queueList">
                                <div id="dndArea" class="placeholder">
                                    <div id="filePicker"></div>
                                    <p>或將照片拖到這裡,並支援截圖貼上功能</p>
                                </div>
                            </div>
                            <div class="statusBar" style="display: none;">
                                <div class="progress">
                                    <span class="text">0%</span>
                                    <span class="percentage"></span>
                                </div>
                                <div class="info"></div>
                                <div class="btns">
                                    <div id="filePicker2"></div>
                                    <div class="uploadBtn">開始上傳</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!--上傳圖片end-->
            </div>
        </div>
    </div>
</div>
<button id="openUpload" type="button" class="btn btn-primary" data-toggle="modal" data-target="#imgModal">上傳圖片</button>
<script>
    $(function () {
        var callback = function (response) {
            if (response.Status == 200) {
                new PNotify({ title: "成功!", text: response.Message, type: 'success' });// 此處使用了Pnotify 外掛== alert
            } else {
                new PNotify({ title: "失敗!", text: response.Message, type: 'error' });
            }
        };


        //開啟模態框-初始化圖片外掛
        $('#imgModal').on('shown.bs.modal', function () {
            _init_upload(callback);
        });
        //關閉模態框-銷燬物件
        $('#imgModal').on('hidden.bs.modal', function () {
            if (typeof (uploader) != "undefined") {
                uploader._destroy();
            }
        });
    });
</script>

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebUpload上傳例項</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    @*<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />*@
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <!--圖片上傳例項樣式 start-->
    <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link href="../vendors/webuploader-0.1.5/webuploader.css" rel="stylesheet" />
    <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
    <link href="../vendors/pnotify/dist/pnotify.custom.min.css" rel="stylesheet" />
    <link href="../vendors/webuploader-0.1.5/style_simple.css?v=1" rel="stylesheet" />
    <link href="~/vendors/custom/css/custom_ask.css" rel="stylesheet" />
    <script src="../vendors/jquery/dist/jquery.min.js"></script>
    <!--圖片上傳例項樣式 end-->
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/Upload/Index">首頁</a>
                <a class="navbar-brand" href="/Upload/Upload">直接上傳</a>
                <a class="navbar-brand" href="/Upload/SimpleUpload">簡單上傳</a>
                <a class="navbar-brand" href="/Upload/ModalUpload">模態框上傳</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav"></ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    <!--圖片上傳例項樣式 JS start-->
    <script src="../vendors/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="../vendors/webuploader-0.1.5/webuploader.min.js"></script>
    <script src="../vendors/pnotify/dist/pnotify.custom.min.js"></script>
    <script src="../vendors/webuploader-0.1.5/upload.js?v=2"></script><!--直接上傳或模態框上傳使用-->
    <script src="~/vendors/webuploader-0.1.5/upload_simple.js"></script><!--簡單上傳使用-->
    <script src="~/vendors/custom/js/custom.js"></script><!--無關緊要的JS-->
    <!--圖片上傳例項樣式 JS end-->
</body>
</html>

執行效果如圖:

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

相關文章