腾讯云cos对象存储C#版本上传

using ConsoleApplication2;
//using QCloud.CosApi.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace WebSocketService
{
public class TXupfile
{
//var Bucket = “temp-1256392453”;
//var Region = “ap-chengdu”; //根据区域需要变更
//var protocol = “http:”;
//var prefix = protocol + “//” + Bucket + “.cos.” + Region + “.myqcloud.com”;
// 上传文件
// NewUpload(prefix, “/dir/demo/web.rar”, “C:\web.rar”);
//删除文件
// NEWDeleteFile(prefix, “/dir/demo/web.rar”);
//下载文件
//FileDownload(prefix, “/dir/demo/0379aeb8-4a31-ec76-e79c-9cde8b021c98.jpg”, “C:\temp\0379aeb8-4a31-ec76-e79c-9cde8b021c98.jpg”); //ok
public string SecretId = “”;//写自己的id
public string SecretKey = “”;//写自己的密钥

    #region 获取签名处理

    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public string gettxkey(string strModel, string pathname, string qheaderlist, string qurlparamlist)
    {

        strModel = strModel.ToLower();
        if (pathname.IndexOf("/") != 0)
        {
            pathname = "/" + pathname;
        } 
        var singtime = ""; 

        //1525180877;1525181777
        var now = Extension.ToUnixTime(DateTime.Now) / 1000; //1536307831;
        var exp = Extension.ToUnixTime(DateTime.Now.AddMinutes(15)) / 1000; //1536309631;
        singtime = now + ";" + exp;
        //http://zzc123-1255082434.cos.ap-shanghai.myqcloud.com/ae.txt?sign=q-sign-algorithm=sha1
        //&q-ak=AKIDMgpmt8LnwzseLsDt9Jfx537Fe5PcRhYH
        //&q-sign-time=1536307831;1536309631
        //&q-key-time=1536307831;1536309631
        //&q-header-list=
        //&q-url-param-list=
        //&q-signature=a4d9fb667134e7ffcf8d70efb993456a5b284463

        string s1 = HmacSha1Sign(singtime, SecretKey);

        string s2 = strModel + "\n" + pathname + "\n" + qurlparamlist + "\n" + qheaderlist + "\n";
        //"put
        /// dir / demo / IMG_0049.JPG

        //
        //"
        string t1 = "";
        t1 = EncryptToSHA1(s2);

        //e07bb035ce2df0b14169517bf87cdd3c52cc04dc
        string s3 = "sha1\n" + singtime + "\n" + t1 + "\n";
        //       "sha1
        //1525180877; 1525181777
        //e07bb035ce2df0b14169517bf87cdd3c52cc04dc
        //"
        string s4 = HmacSha1Sign(s3, s1);
        //ec56b2de542469df437d72662e3e3a262d747468
        var authorization = "q-sign-algorithm=sha1&q-ak=" + SecretId + "&q-sign-time=" + singtime + "&q-key-time=" + singtime + "&q-header-list=" + qheaderlist + "&q-url-param-list=" + qurlparamlist + "&q-signature=" + s4;
        return authorization;
        //q-sign-algorithm=sha1&q-ak=AKIDjHaqtiVq44sSownVv62kCPM3VjjV2Ueb&q-sign-time=1525180877;1525181777&q-key-time=1525180877;1525181777&q-header-list=&q-url-param-list=&q-signature=ec56b2de542469df437d72662e3e3a262d747468
    }
    public string EncryptToSHA1(string str)
    {
        var buffer = Encoding.UTF8.GetBytes(str);
        var data = System.Security.Cryptography.SHA1.Create().ComputeHash(buffer);

        var sb = new StringBuilder();
        foreach (var t in data)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString().ToLower();
    }

    /// 
    /// HMAC-SHA1加密算法
    /// 
    /// 密钥
    /// 源文
    /// 
    public static string HmacSha1Sign(string EncryptText, string EncryptKey)
    {
        HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.Default.GetBytes(EncryptKey));
        byte[] RstRes = myHMACSHA1.ComputeHash(Encoding.Default.GetBytes(EncryptText));
        StringBuilder EnText = new StringBuilder();
        foreach (byte Byte in RstRes)
        {
            EnText.AppendFormat("{0:x2}", Byte);
        }
        return EnText.ToString();
    }
    #endregion

    #region  文件处理,上传,下载,删除


    /// 
    /// put 方式上传文件
    /// 
    /// 路径
    /// 存的地址
    /// 本地文件地址
    /// 
    public string NewUpload(string url, string remotePath, string localPath)
    {



        var sign = gettxkey("put", remotePath, "", "");


        string strurl = url + remotePath + "?sign=" + sign;
        return HttpPut(strurl, localPath, sign);

    }
    public string HttpPut(string inUrl, string inFilePath, string sign)
    {
        //服务器路径      
        string isok = "ok";

        //文件路径      
        //   string fileName = "mysales.txt";

        // 得到文件名,文件扩展名字,服务器路径

        // 创建WebClient实例
        WebClient myWebClient = new WebClient();//header.Add("Authorization", sign);
        myWebClient.Headers.Add("Authorization", sign);
        //访问权限设置      
        myWebClient.Credentials = CredentialCache.DefaultCredentials;

        // 要上传的文件
        FileStream fs = new FileStream(inFilePath, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        try
        {
            byte[] postArray = br.ReadBytes((int)fs.Length);
            Stream postStream = myWebClient.OpenWrite(inUrl, "PUT");
            if (postStream.CanWrite)
            {
                postStream.Write(postArray, 0, postArray.Length);

            }
            else
            {

            }
            postStream.Close();
        }
        catch (WebException errMsg)
        {
            isok = errMsg.Message;
        }
        return isok;
    }
    /// 
    /// 删除文件
    /// 
    /// 
    /// 文件路径
    /// 
    public string NEWDeleteFile(string url, string remotePath)
    {

        string message = "ok";
        var sign = gettxkey("DELETE", remotePath, "", "");

        string strurl = url + remotePath;

        var request = (HttpWebRequest)WebRequest.Create(strurl);

        request.Method = "DELETE";
        request.Headers.Add("Authorization", sign);

        try
        {
            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


        }
        catch (Exception ex)
        {
            message = ex.Message;
        }
        return message;
    }
    /// 
    /// 文件下载
    /// 
    /// 
    /// 下载地址
    /// 保存地址
    /// 
    public string FileDownload(string url, string remotePath, string path)
    {

        string strisok = "ok";
        string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp";
        System.IO.Directory.CreateDirectory(tempPath);  //创建临时文件目录
        string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(path) + ".temp"; //临时文件
        if (System.IO.File.Exists(tempFile))
        {
            System.IO.File.Delete(tempFile);    //存在则删除
        }
        try
        {
            FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url + remotePath) as HttpWebRequest;
            request.Method = "get";
            var sign = gettxkey("get", remotePath, "", "");
            request.Headers.Add("Authorization", sign);
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();
            //创建本地文件写入流
            //Stream stream = new FileStream(tempFile, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                //stream.Write(bArr, 0, size);
                fs.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }
            //stream.Close();
            fs.Close();
            responseStream.Close();
            System.IO.File.Move(tempFile, path);
            //删除文件夹 tempPath
            Directory.Delete(tempPath, true);
        }
        catch (Exception ex)
        {
            strisok = ex.Message;
        }

        return strisok;

    }
    #endregion


}

}

你可能感兴趣的:(腾讯云cos对象存储C#版本上传)