WebApi兩種上傳圖片


一、表單提交:

 #region 表單提上傳圖片

        [HttpPost, System.Web.Http.Cors.EnableCors(origins: "*", headers: "*", methods: "*")]
        public async Task<string> ImgFormUploadToken()
        {
            ResultInfo resinfo = new ResultInfo();
            //獲取驗證token
            string accessToken = HttpContext.Current.Request.Params["accessToken"];
            if (string.IsNullOrEmpty(accessToken))
                return resinfo.ToString();

            string valaidUrl = Klongiot.volunteers.FileUpload.Models.ConstantVar.imgLoadTokenWebApi + "Values/IsCheckToken";
            resinfo = await Kinglong.Common.HttpHelper.GetOauthPostResInfo(valaidUrl, accessToken, null);
            //驗證失敗
            if (!resinfo.res)
            {
                resinfo.info = "token驗證失敗!無權限上傳圖片!";
                return resinfo.ToString();
            }

            return await ImgFormUpload();
        }

        [HttpPost]
        public async Task<string> ImgFormUpload()
        {

            Kinglong.Common.ResultInfo cResInfo = new Kinglong.Common.ResultInfo();
            //檢查是否 multipart/form-data
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                cResInfo.info = "沒有要上傳的圖片!";
                return cResInfo.ToString();
            }

            string folderName = HttpContext.Current.Request.Params["folderName"];
            string fileName = HttpContext.Current.Request.Params["fileName"];

            //文件保存目錄路徑
            string saveTempPath = "/UpLoadFiles";
            string resTempPath = "";
            if (!string.IsNullOrEmpty(folderName))
            {
                resTempPath += "/" + folderName;
                saveTempPath += "/" + folderName;
            }

            string dirTempPath = HttpContext.Current.Server.MapPath(saveTempPath);
            if (!System.IO.Directory.Exists(dirTempPath))
            {
                System.IO.Directory.CreateDirectory(dirTempPath);
            }
            //判斷目錄是否存在

            //設置上傳目錄
            MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(dirTempPath);
            await Request.Content.ReadAsMultipartAsync(provider);

            foreach (MultipartFileData file in provider.FileData)
            {
                //這里獲取含有雙引號'" '
                string filename = file.Headers.ContentDisposition.FileName.Trim('"');

                //獲取對應文件后綴名
                string fileExt = filename.Split('.')[1];
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(file.LocalFileName);
                //fileinfo.Name 上傳后的文件路徑 此處不含后綴名
                //修改文件名 添加后綴名
                if (string.IsNullOrEmpty(fileName))
                    fileName = Guid.NewGuid().ToString();
                resTempPath += "/" + fileName + "." + fileExt;
                string saveUrl = dirTempPath + "/" + fileName + "." + fileExt;
                try
                {
                    fileInfo.MoveTo(saveUrl);
                    cResInfo.attr["path"] = resTempPath;
                    cResInfo.res = true;
                }
                catch (FileLoadException exf)
                {
                    continue;

                }
            }
            cResInfo.StatusCode = "200";
            cResInfo.info = "success";
            return cResInfo.ToString();
        }

        #endregion
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link href="Content/quoteJs/webuploader/webuploader.css" rel="stylesheet" />

    <script src="Content/quoteJs/jquery-2.1.4.min.js"></script>
    <script src="Content/quoteJs/webuploader/webuploader.js"></script>
    <script src="Content/quoteJs/jquery.form.js"></script>
    <script type="text/javascript">
        $(function () {

            // 初始化Web Uploader
            var uploader = WebUploader.create({
                // 選完文件后,是否自動上傳。
                auto: true,
                // swf文件路徑
                swf: 'Content/quoteJs/webuploader/Uploader.swf',
                // 文件接收服務端。
                //server: 'http://192.168.1.147:91/api/Upload/ImgFormUpload',
                server: 'http://192.168.1.147:91/api/Upload/ImgBasicUpload',
                method:'POST',
                // 選擇文件的按鈕。可選。
                // 內部根據當前運行是創建,可能是input元素,也可能是flash.
                pick: '#filePicker',
                withCredentials: true,
                sendAsBinary:true,
                // 只允許選擇圖片文件。
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/*'
                }
            });
            var $list = $('#fileList');
            uploader.on('fileQueued', function (file) {
                var $li = $(
                '<div id="' + file.id + '" class="file-item thumbnail">' +
                '<img>' +
                '<div class="info">' + file.name + '</div>' +
                '</div>'
                ),
                $img = $li.find('img');
                // $list為容器jQuery實例
                $list.append($li);
                // 創建縮略圖
                // 如果為非圖片文件,可以不用調用此方法。
                // thumbnailWidth x thumbnailHeight 為 100 x 100
                uploader.makeThumb(file, function (error, src) {
                    if (error) {
                        $img.replaceWith('<span>不能預覽</span>');
                        return;
                    }
                    $img.attr('src', src);
                }, 50, 50);
            });

            // 文件上傳過程中創建進度條實時顯示。
            uploader.on('uploadProgress', function (file, percentage) {
                var $li = $('#' + file.id),
                $percent = $li.find('.progress span');
                // 避免重復創建
                if (!$percent.length) {
                    $percent = $('<p class="progress"><span></span></p>')
                    .appendTo($li)
                    .find('span');
                }
                $percent.css('width', percentage * 100 + '%');
            });

            //uploader.on('uploadBeforeSend', function (obj, data, headers) {
            //    $.extend(headers, {
            //        "Origin": "*"

            //    });
            //});

            // 文件上傳成功,給item添加成功class, 用樣式標記上傳成功。
            uploader.on('uploadSuccess', function (file) {
                $('#' + file.id).addClass('upload-state-done');
            });
            // 文件上傳失敗,顯示上傳出錯。
            uploader.on('uploadError', function (file) {
                var $li = $('#' + file.id),
                $error = $li.find('div.error');
                // 避免重復創建
                if (!$error.length) {
                    $error = $('<div class="error"></div>').appendTo($li);
                }
                $error.text('上傳失敗');
            });
            // 完成上傳完了,成功或者失敗,先刪除進度條。
            uploader.on('uploadComplete', function (file) {
                $('#' + file.id).find('.progress').remove();
            });

        });
    </script>
</head>
<body>
    <form>
        <!--dom結構部分-->
        <div id="uploader-demo">
            <!--用來存放item-->
            <div id="fileList" class="uploader-list"></div>
            <div id="filePicker">選擇圖片</div>
        </div>

    </form>
</body>

第二種basic64上傳,作app上傳圖片使用比較多。

#region 二進制文件上傳認證

        /// <summary>
        /// 需要走oauth 驗證 才能上傳圖片
        /// </summary>
        /// <param name="quePara"></param>
        /// <returns></returns>

        [HttpPost, System.Web.Http.Cors.EnableCors(origins: "*", headers: "*", methods: "*")]
        public async Task<string> ImgBasicUploadToken([FromBody]JObject quePara)
        {
            ResultInfo resinfo = new ResultInfo();
            //獲取驗證token
            string accessToken = quePara["accessToken"] == null ? "" : quePara["accessToken"].ToString();
            if (string.IsNullOrEmpty(accessToken))
                return resinfo.ToString();

            Dictionary<string, string> postPara = new Dictionary<string, string>();
            postPara["dictPara"] = "12";
            string valaidUrl = Klongiot.volunteers.FileUpload.Models.ConstantVar.imgLoadTokenWebApi + "Values/IsCheckToken";
            resinfo = await Kinglong.Common.HttpHelper.GetOauthPostResInfo(valaidUrl, accessToken, postPara);
            //驗證失敗
            if (!resinfo.res)
            {
                resinfo.info = "token驗證失敗!無權限上傳圖片!";
                return resinfo.ToString();
            }

            return await ImgBasicUpload(quePara);
        }

        /// <summary>
        /// 局域網不需要驗證即可上傳
        /// </summary>
        /// <param name="quePara"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> ImgBasicUpload([FromBody]JObject quePara)
        {
            ResultInfo cResInfo = new ResultInfo();
            if (quePara == null)
            {
                return cResInfo.ToString();
            }
            string file = quePara["file"] == null ? "" : quePara["file"].ToString();
            string folderName = quePara["folderName"] == null ? "" : quePara["folderName"].ToString();
            string fileName = quePara["fileName"] == null ? "" : quePara["fileName"].ToString();

            if (string.IsNullOrEmpty(file))
                return cResInfo.ToString();
            try
            {
                byte[] bt = Convert.FromBase64String(file);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(bt);
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);
                string saveTempPath = "/UpLoadFiles";

                string resTempPath = "";
                if (!string.IsNullOrEmpty(folderName))
                {
                    saveTempPath += "/" + folderName;
                    resTempPath += "/" + folderName;
                }
                string dirTempPath = System.Web.Hosting.HostingEnvironment.MapPath(saveTempPath);
                // string dirTempPath = HttpContext.Current.Server.MapPath(saveTempPath);
                if (!System.IO.Directory.Exists(dirTempPath))
                {
                    System.IO.Directory.CreateDirectory(dirTempPath);
                }

                //如果沒有名字使用guid命名
                if (string.IsNullOrEmpty(fileName))
                    fileName = Guid.NewGuid().ToString();
                resTempPath += "/" + fileName + ".jpg";
                dirTempPath += "/" + fileName + ".jpg";

                bitmap.Save(dirTempPath);
                cResInfo.attr["path"] = resTempPath;
                cResInfo.res = true;
            }
            catch (Exception ex)
            {
                throw;
            }

            return cResInfo.ToString();
        }

        #endregion
       $(function () {
            //初始化
            $('#file').ImgBasic64Upload({
                isEnableChange: true
                , url: "/api/Upload/ImgBasicUpload"
                , ajaxSucCall: function (d) {
                    alert(JSON.stringify(d));
                }
            });


        });





; (function ($) {
    //主方法
    $.fn.ImgBasic64Upload = function (optOrMenthName, _options) {
        // 方法調用
        var $this = $(this),
        thsId = $this.attr('id');
        optOrMenthName = optOrMenthName || {};
        var stateOption = $this.data(thsId);
        if (stateOption) {
            $.fn.ImgBasic64Upload.Options = $.extend(stateOption, optOrMenthName);
        } else {
            $.fn.ImgBasic64Upload.Options = $.extend(defaults, optOrMenthName);
            $this.data(thsId, $.fn.ImgBasic64Upload.Options);
        }

        if (typeof optOrMenthName == 'string') {
            return methods[method](this, _options);
        }

        if ($.fn.ImgBasic64Upload.Options.isEnableChange) {
            $this.on('change', function (e) {
                methods['fileOnChange']($this,e);
            });
        }
    };

    var defaults = {
        //是否啟用fileOnchange事件
        isEnableChange: false,
        //是否啟用縮略圖
        isDramImg: true
        , outputFormat: ''
        //縮略圖寬
        , width: 90
        //縮略圖高
        , height: 90
        , imgBasic64: ''
        //圖片上傳文件夾
        , folderName: 'default'
        //自定義文件名
        , fileName: ''
        ,accessToken:undefined
        , url: undefined
        , ajaxData: {}
        ,ajaxSucCall:function(d){

        }
    };

    var methods = {
        fileOnChange:function($this,e){
            var file = $this[0].files[0];
            var val = $this.val().split('.')[1];
            if (val == 'png' || val == 'jpg' || val == 'jpeg' || val == 'JPEG' || val == 'JPG' || val == 'PNG') {
                //轉換文件64位
                var ready = new FileReader();
                /*開始讀取指定的Blob對象或File對象中的內容. 當讀取操作完成時,readyState屬性的值會成為DONE,如果設置了onloadend事件處理程序,則調用之.同時,result屬性中將包含一個data: URL格式的字符串以表示所讀取文件的內容.*/
                ready.readAsDataURL(file);
                ready.onload = function () {
                    $.fn.ImgBasic64Upload.Options.imgBasic64 = this.result;
                    //啟用壓縮圖片
                    if ($.fn.ImgBasic64Upload.Options.isDramImg == true) {
                        methods.dramImg($this);
                    } else {
                        uploadImg(basic64, "/api/Upload/ImgBasicUploadToken", "userimg", "001", undefined);
                    }
                }
            } else {
                layer.alert('請選擇圖片上傳');

            }
        },
        ////圖片壓縮
        dramImg: function dramImg(ths, paras) {
            var canvas = document.createElement('CANVAS');
            var ctx = canvas.getContext('2d');
            var imgWidth = 0, imgHeight = 0, offsetX = 0, offsetY = 0;
            var resultBasic = undefined;
            var img = new Image;
            img.crossOrigin = 'Anonymous';
            img.src = $.fn.ImgBasic64Upload.Options.imgBasic64;
            img.onload = function () {
                imgWidth = img.width;
                imgHeight = img.height;
                if (imgWidth > imgHeight) {
                    imgWidth = $.fn.ImgBasic64Upload.Options.width * imgWidth / imgHeight;
                    imgHeight = $.fn.ImgBasic64Upload.Options.width;
                    offsetX = -Math.round((imgWidth - $.fn.ImgBasic64Upload.Options.width) / 2);
                } else {
                    imgHeight = $.fn.ImgBasic64Upload.Options.width * imgHeight / imgWidth;
                    imgWidth = $.fn.ImgBasic64Upload.Options.width;
                    offsetY = -Math.round((imgHeight - $.fn.ImgBasic64Upload.Options.width) / 2);
                }

                imgHeight = imgHeight != NaN ? imgHeight : 0;
                offsetY = offsetY != NaN ? offsetY : 0;

                canvas.height = $.fn.ImgBasic64Upload.Options.height;
                canvas.width = $.fn.ImgBasic64Upload.Options.width;
                ctx.drawImage(img, offsetX, offsetY, imgWidth, imgHeight);
                if (!$.fn.ImgBasic64Upload.Options.outputFormat || $.fn.ImgBasic64Upload.Options.outputFormat == '')
                    outputFormat = 'image/jpeg';
                $.fn.ImgBasic64Upload.Options.imgBasic64 = canvas.toDataURL(outputFormat);
                methods.uploadImg(ths);
                //上傳圖片
            };
            //while (!resultBasic) {


            //}
            //return resultBasic;
        },
        uploadImg: function (ths) {
            
            var opt = $.fn.ImgBasic64Upload.Options;
            //if (!opt.accessToken) {
            //    alert("accessToken不能為空!");
            //    return false;
            //}
            if (!opt.url) {
                alert("圖片上傳Url不能為空!");
                return false;
            }
            opt.ajaxData = $.extend(opt.ajaxData, {
                "file": opt.imgBasic64.split(",")[1]
                , 'folderName': opt.folderName, "fileName": opt.fileName
                , "accessToken": opt.accessToken
            });

            $.ajax({
                type: 'POST',
                url: opt.url,
                //contentType: "application/json",
                data: opt.ajaxData,
                dataType: 'JSON',
                success: function (data) {
                    if (typeof ($.fn.ImgBasic64Upload.Options.ajaxSucCall) == 'function') {
                        $.fn.ImgBasic64Upload.Options.ajaxSucCall(data);
                    }
                },
                error: function (data) {
                }
            });
        }

    }
    //methods 結束

})(jQuery);

 


免責聲明!

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



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