微信小程序基于腾讯云对象存储的图片上传

小说:支付宝挂机赚钱作者:乙扁平更新时间:2019-02-23字数:38521

将尼古拉打出去之后,叶扬在那里摸着自己的拳头,脸上露出了一抹不屑的表情。

淘最热点是什么机构

一路上可谓是风平浪静并没有明教等人预想之中的那样危机四伏,毕竟不说明教众人就是朝廷和武林的眼中钉。
“你可以选择拒绝的。”刘皓双手交叉叠加在胸前,饶有兴致的看着渡会怎么选择。

尼尔虽然有点不情愿,不过却没有拒绝而是将龙珠交给了刘皓,他很清楚大长老既然这么决定,绝对有他的道理。

        在使用腾讯云对象存储之前,公司一直使用的是传统的FTP的上传模式,而随着用户量的不断增加,FTP所暴露出来的问题也越来越多,1.传输效率低,上传速度慢。2.时常有上传其他文件来攻击服务器,安全上得不到保障。所以我们在经过慎重考虑觉得使用第三方的云存储服务。

         在最开始的时候我们在腾讯云与阿里云中选择,最终我们选择腾讯云,腾讯云在文件上传用时方面的性能比较突出,文件越大表现越好;在下载用时方面表现略优于阿里云;文件删除用时方面总体速度略逊于,但在不同大小文件删除用时上都比较稳定。当然这与我们主要用于开发微信小程序是有着密切的关系。

        在我们酷客多小程序使用腾讯云对象存储的时候除了直接使用 API 接口外,COS 提供了丰富多样的 SDK 给我们使用,可是在他提供的SDK中并没有发现我们Asp.net相关的SDK

在一番百度和一顿操作终于让我找到啦!看到没,只能说隐藏的真深,而且还是历史版本的,但是不管怎么样我们还是找到啦

         找到C#的SDK,下载下来 (附上C#版本SDK的下载地址 C# SDK github项目下载地址)然后按照SDK中提供的方法,就可以成功上传!

         然而并没有这么简单,当我们使用SDK中的方法的时候发现,SDK中的方法只适用于,绝对路径地址的文件上传!也就是并不满足我们ASP.Net中使用文件域上传文件。此时我们只有对方法进行改造!

附上改造过后代码:

        /// <summary>
        /// 文件流上传
        /// 说明: 酷客多小程序
        /// 其中分片上传使用SliceUploadInit SliceUploadData SliceUploadFinihs
        /// </summary>
        /// <param name="bucketName">bucket名称</param>
        /// <param name="remotePath">远程文件路径</param>
        /// <param name="localPath">本地文件路径</param>
        /// <param name="parameterDic">参数Dictionary</param>
        /// <returns></returns>
        public string UploadFile(string bucketName, string remotePath, Stream file, string filename,Dictionary<string, string> parameterDic = null)
        {
            if (remotePath.EndsWith("/"))
            {
                return constructResult(ERRORCode.ERROR_CODE_PARAMETER_ERROE, "file path can not end with "/"");
            }

            string bizAttribute = "";
            if (parameterDic != null && parameterDic.ContainsKey(CosParameters.PARA_BIZ_ATTR))
                bizAttribute = parameterDic[CosParameters.PARA_BIZ_ATTR];

            int insertOnly = 1;
            if (parameterDic != null && parameterDic.ContainsKey(CosParameters.PARA_INSERT_ONLY))
            {
                try
                {
                    insertOnly = Int32.Parse(parameterDic[CosParameters.PARA_INSERT_ONLY]);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return constructResult(ERRORCode.ERROR_CODE_PARAMETER_ERROE, "parameter insertOnly value invalidate");
                }
            }
            return Upload(bucketName, remotePath, file, filename, bizAttribute, insertOnly);

        }
        /// <summary>
        /// 单个文件上传
        /// 说明: 酷客多小程序
        /// <param name="bucketName">bucket名称</param>
        /// <param name="remotePath">远程文件路径</param>
        /// <param name="localPath">本地文件路径</param>
        /// <param name="biz_attr">biz_attr属性</param>
        /// <param name="insertOnly">同名文件是否覆盖</param>
        /// <returns></returns>
        public string Upload(string bucketName, string remotePath, Stream file,string filename,
                                  string bizAttribute = "", int insertOnly = 1)
        {

            var url = generateURL(bucketName, remotePath);
            var sha1 = SHA1.GetFileSHA1(file);
            var data = new Dictionary<string, object>();
            data.Add("op", "upload");
            data.Add("sha", sha1);
            data.Add("biz_attr", bizAttribute);
            data.Add("insertOnly", insertOnly);

            var expired = getExpiredTime();
            var sign = Sign.Signature(appId, secretId, secretKey, expired, bucketName);
            var header = new Dictionary<string, string>();
            header.Add("Authorization", sign);


            return httpRequest.SendRequest(url, ref data, HttpMethod.Post, ref header, timeOut, file, filename);
        }

 

       #region 直接上传文件流
       public string SendRequest(string url, ref Dictionary<string, object> data, HttpMethod requestMethod,
       ref Dictionary<string, string> header, int timeOut, Stream file,string filename, long offset = -1, int sliceSize = 0)
        {
            try
            {
                //Console.WriteLine("url:" + url);
                System.Net.ServicePointManager.Expect100Continue = false;
                if (requestMethod == HttpMethod.Get)
                {
                    var paramStr = "";
                    foreach (var key in data.Keys)
                    {
                        paramStr += string.Format("{0}={1}&", key, HttpUtility.UrlEncode(data[key].ToString()));
                    }
                    paramStr = paramStr.TrimEnd("&");
                    url += (url.EndsWith("?") ? "&" : "?") + paramStr;
                }

                request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Accept = CosDefaultValue.ACCEPT;
                request.KeepAlive = true;
                request.UserAgent = CosDefaultValue.USER_AGENT_VERSION;
                request.Timeout = timeOut;
                foreach (var key in header.Keys)
                {
                    if (key == "Content-Type")
                    {
                        request.ContentType = header[key];
                    }
                    else
                    {
                        request.Headers.Add(key, header[key]);
                    }
                }
                if (requestMethod == HttpMethod.Post)
                {
                    request.Method = requestMethod.ToString().ToUpper();
                    var memStream = new MemoryStream();
                    if (header.ContainsKey("Content-Type") && header["Content-Type"] == "application/json")
                    {
                        var json = JsonConvert.SerializeObject(data);
                        var jsonByte = Encoding.GetEncoding("utf-8").GetBytes(json.ToString());
                        memStream.Write(jsonByte, 0, jsonByte.Length);
                    }
                    else
                    {
                        var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                        var beginBoundary = Encoding.ASCII.GetBytes("
--" + boundary + "
");
                        var endBoundary = Encoding.ASCII.GetBytes("
--" + boundary + "--
");
                        request.ContentType = "multipart/form-data; boundary=" + boundary;

                        var strBuf = new StringBuilder();
                        foreach (var key in data.Keys)
                        {
                            strBuf.Append("
--" + boundary + "
");
                            strBuf.Append("Content-Disposition: form-data; name="" + key + ""

");
                            strBuf.Append(data[key].ToString());
                        }
                        var paramsByte = Encoding.GetEncoding("utf-8").GetBytes(strBuf.ToString());
                        memStream.Write(paramsByte, 0, paramsByte.Length);

                        memStream.Write(beginBoundary, 0, beginBoundary.Length);


                        var fileStream = file;

                        const string filePartHeader =
                            "Content-Disposition: form-data; name="fileContent"; filename="{0}"
" +
                            "Content-Type: application/octet-stream

";
                        var headerText = string.Format(filePartHeader, filename);
                        var headerbytes = Encoding.UTF8.GetBytes(headerText);
                        memStream.Write(headerbytes, 0, headerbytes.Length);

                        if (offset == -1)
                        {
                            var buffer = new byte[1024];
                            int bytesRead;
                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                memStream.Write(buffer, 0, bytesRead);
                            }
                        }
                        else
                        {
                            var buffer = new byte[sliceSize];
                            int bytesRead;
                            fileStream.Seek(offset, SeekOrigin.Begin);
                            bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                            memStream.Write(buffer, 0, bytesRead);
                        }
                        fileStream.Close();

                        memStream.Write(endBoundary, 0, endBoundary.Length);
                    }
                    request.ContentLength = memStream.Length;
                    var requestStream = request.GetRequestStream();
                    memStream.Position = 0;
                    var tempBuffer = new byte[memStream.Length];
                    memStream.Read(tempBuffer, 0, tempBuffer.Length);
                    memStream.Close();

                    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                    requestStream.Close();

                    //Console.WriteLine(strBuf.ToString());
                }

                //Console.WriteLine(request.ContentType.ToString());


                var response = request.GetResponse();
                using (var s = response.GetResponseStream())
                {
                    var reader = new StreamReader(s, Encoding.UTF8);
                    return reader.ReadToEnd();
                }
            }
            catch (WebException we)
            {
                if (we.Status == WebExceptionStatus.ProtocolError)
                {
                    using (var s = we.Response.GetResponseStream())
                    {
                        var reader = new StreamReader(s, Encoding.UTF8);
                        return reader.ReadToEnd();
                    }
                }
                else
                {
                    throw we;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

使用上面改造过后的方法直接传入文件流即可通过文本域的方式上传文件到腾讯云上面去!

Asp.net 腾讯云对象存储的相关使用就介绍到这里,下次我们将介绍如何使用腾讯云对象存储打造图片管理模块。

-----酷客多小程序   刘崇杰

编辑:秉戏扁

发布:2019-02-23 04:59:08

当前文章:http://adsl66.com/83063.html

支付宝,nb,赚钱宝跑分 云赚打码平台怎么样 买高价手机刷广告赚钱 苹果挂机赚钱平台 淘宝联盟佣金没到账 我现在有十台电脑能做什么赚钱? 屠龙破晓赚人民币方法 苹果锁机项目免费教程

60307 28574 56690 61588 43612 8526330709 20216 20818

我要说两句: (0人参与)

发布