欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-03 11:06:21
在使用腾讯云对象存储之前,公司一直使用的是传统的ftp的上传模式,而随着用户量的不断增加,ftp所暴露出来的问题也越来越多,1.传输效率低,上传速度慢。2.时常有上传其他文...

在使用腾讯云对象存储之前,公司一直使用的是传统的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("\r\n--" + boundary + "\r\n");
            var endboundary = encoding.ascii.getbytes("\r\n--" + boundary + "--\r\n");
            request.contenttype = "multipart/form-data; boundary=" + boundary;
            var strbuf = new stringbuilder();
            foreach (var key in data.keys)
            {
              strbuf.append("\r\n--" + boundary + "\r\n");
              strbuf.append("content-disposition: form-data; name=\"" + key + "\"\r\n\r\n");
              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}\"\r\n" +
              "content-type: application/octet-stream\r\n\r\n";
            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;
      }
    }

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

总结

以上所述是小编给大家介绍的微信小程序基于腾讯云对象存储的图片上传功能,希望对大家有所帮助