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);

 

posted @ 2018-01-08 19:14  黄子清  阅读(8188)  评论(0编辑  收藏  举报