14
2015
04

简单对七牛.Net API管理文件进行简单封装的类

//封装类代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Qiniu.Conf;
using Qiniu.RS;
using Qiniu.RPC;
using Qiniu.RSF;
using Qiniu.IO;
using Qiniu.IO.Resumable;
using System.IO;
using System.Web;
using System.Drawing.Imaging;
using Qiniu.FileOp;
using System.Net;
//要先引用qiniu的dll文件
namespace ypsuit.common.QiniuHelper
{
    public class QiniuHelper
    {
        /// <summary>
        /// cdnPath为网站服务器本地路径,本地备份一份,再上传到七牛空间一份
        /// </summary>
        private static readonly string cdnPath = DataHelper.GetAbsolutePath(CommonFun.GetConfigData(DataConfigKey.Qiniu.ToString(), DataConfigAttr.CDN_PATH.ToString()));
        /// <summary>
        /// 空间名
        /// </summary>
        public static readonly string bucket = CommonFun.GetConfigData(DataConfigKey.Qiniu.ToString(), DataConfigAttr.BUCKET.ToString());
        /// <summary>
        /// 七牛外域名
        /// </summary>
        public static readonly string Domain = CommonFun.GetConfigData(DataConfigKey.Qiniu.ToString(), DataConfigAttr.DOMAIN.ToString());
        /// <summary>
        /// 在网站/程序初始化时调用一次
        /// </summary>
        public static void Init()
        {
            //设置权限key
            Qiniu.Conf.Config.ACCESS_KEY = CommonFun.GetConfigData(DataConfigKey.Qiniu.ToString(), DataConfigAttr.ACCESS_KEY.ToString());
            //设置密匙key
            Qiniu.Conf.Config.SECRET_KEY = CommonFun.GetConfigData(DataConfigKey.Qiniu.ToString(), DataConfigAttr.SECRET_KEY.ToString());
        }
        #region 查看单个文件属性信息
        /// <summary>
        /// 查看单个文件属性信息
        /// </summary>
        /// <param name="bucket">七牛云存储空间名</param>
        /// <param name="key">文件key</param>
        public static void Stat(string bucket, string key)
        {
            RSClient client = new RSClient();
            Entry entry = client.Stat(new EntryPath(bucket, key));
            if (entry.OK)
            {
                Console.WriteLine("Hash: " + entry.Hash);
                Console.WriteLine("Fsize: " + entry.Fsize);
                Console.WriteLine("PutTime: " + entry.PutTime);
                Console.WriteLine("MimeType: " + entry.MimeType);
                Console.WriteLine("Customer: " + entry.Customer);
            }
            else
            {
                Console.WriteLine("Failed to Stat");
            }
        }
        #endregion
        /// <summary>
        /// 复制单个文件
        /// </summary>
        /// <param name="bucketSrc">需要复制的文件所在的空间名</param>
        /// <param name="keySrc">需要复制的文件key</param>
        /// <param name="bucketDest">目标文件所在的空间名</param>
        /// <param name="keyDest">标文件key</param>
        public static void Copy(string bucketSrc, string keySrc, string bucketDest, string keyDest)
        {
            RSClient client = new RSClient();
            CallRet ret = client.Copy(new EntryPathPair(bucketSrc, keySrc, bucketDest, keyDest));
            if (ret.OK)
            {
                Console.WriteLine("Copy OK");
            }
            else
            {
                Console.WriteLine("Failed to Copy");
            }
        }
        /// <summary>
        /// 移动单个文件
        /// </summary>
        /// <param name="bucketSrc">需要移动的文件所在的空间名</param>
        /// <param name="keySrc">需要移动的文件</param>
        /// <param name="bucketDest">目标文件所在的空间名</param>
        /// <param name="keyDest">目标文件key</param>
        public static void Move(string bucketSrc, string keySrc, string bucketDest, string keyDest)
        {
            Console.WriteLine("\n===> Move {0}:{1} To {2}:{3}",
            bucketSrc, keySrc, bucketDest, keyDest);
            RSClient client = new RSClient();
            new EntryPathPair(bucketSrc, keySrc, bucketDest, keyDest);
            CallRet ret = client.Move(new EntryPathPair(bucketSrc, keySrc, bucketDest, keyDest));
            if (ret.OK)
            {
                Console.WriteLine("Move OK");
            }
            else
            {
                Console.WriteLine("Failed to Move");
            }
        }
        /// <summary>
        /// 删除单个文件
        /// </summary>
        /// <param name="bucket">文件所在的空间名</param>
        /// <param name="key">文件key</param>
        public static void Delete(string bucket, string key)
        {
            //Console.WriteLine("\n===> Delete {0}:{1}", bucket, key);
            RSClient client = new RSClient();
            CallRet ret = client.Delete(new EntryPath(bucket, key));
            //if (ret.OK)
            //{
            //    Console.WriteLine("Delete OK");
            //}
            //else
            //{
            //    Console.WriteLine("Failed to delete");
            //}
        }
        /// <summary>
        /// 批量获取文件信息
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="keys"></param>
        public static void BatchStat(string bucket, string[] keys)
        {
            RSClient client = new RSClient();
            List<EntryPath> EntryPaths = new List<EntryPath>();
            foreach (string key in keys)
            {
                Console.WriteLine("\n===> Stat {0}:{1}", bucket, key);
                EntryPaths.Add(new EntryPath(bucket, key));
            }
            client.BatchStat(EntryPaths.ToArray());
        }
        /// <summary>
        /// 批量复制
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="keys"></param>
        public static void BatchCopy(string bucket, string[] keys)
        {
            List<EntryPathPair> pairs = new List<EntryPathPair>();
            foreach (string key in keys)
            {
                EntryPathPair entry = new EntryPathPair(bucket, key, Guid.NewGuid().ToString());
                pairs.Add(entry);
            }
            RSClient client = new RSClient();
            client.BatchCopy(pairs.ToArray());
        }
        /// <summary>
        /// 批量移动
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="keys"></param>
        public static void BatchMove(string bucket, string[] keys)
        {
            List<EntryPathPair> pairs = new List<EntryPathPair>();
            foreach (string key in keys)
            {
                EntryPathPair entry = new EntryPathPair(bucket, key, Guid.NewGuid().ToString());
                pairs.Add(entry);
            }
            RSClient client = new RSClient();
            client.BatchMove(pairs.ToArray());
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="keys"></param>
        public static void BatchDelete(string bucket, string[] keys)
        {
            RSClient client = new RSClient();
            List<EntryPath> EntryPaths = new List<EntryPath>();
            foreach (string key in keys)
            {
                //Console.WriteLine("\n===> Stat {0}:{1}", bucket, key);
                EntryPaths.Add(new EntryPath(bucket, key));
            }
            client.BatchDelete(EntryPaths.ToArray());
        }
        /// <summary>
        /// 列出所有文件信息
        /// </summary>
        /// <param name="bucket"></param>
        public static List<DumpItem> List(int limit = 100, string prefix = "")
        {
            RSFClient rsf = new RSFClient(bucket);
            rsf.Prefix = prefix;
            rsf.Limit = limit;
            List<DumpItem> list = new List<DumpItem>();
            List<DumpItem> items;
            while ((items = rsf.Next()) != null)
            {
                list.AddRange(items);
                //todo
            }
            return list;
        }
        /// <summary>
        /// 普通上传文件
        /// key必须采用utf8编码,如使用非utf8编码访问七牛云存储将反馈错误
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="key">上传后的路径</param>
        /// <param name="fname">要上传的文件路径(文件必须存在)</param>
        public static PutRet PutFile(string key, string fname)
        {
            if (key.IndexOf('.') == -1) key += Path.GetExtension(fname);
            var policy = new PutPolicy(bucket, 3600);
            string upToken = policy.Token();
            PutExtra extra = new PutExtra();
            IOClient client = new IOClient();
            //client.PutFinished += (o, retTemp) =>
            //{
            //    if (retTemp.StatusCode == HttpStatusCode.OK)
            //    {
            //    }
            //    else if (retTemp.StatusCode == HttpStatusCode.BadGateway ||
            //        retTemp.StatusCode == HttpStatusCode.BadRequest ||
            //        retTemp.StatusCode == HttpStatusCode.GatewayTimeout ||
            //        retTemp.StatusCode == HttpStatusCode.GatewayTimeout ||
            //        retTemp.StatusCode == HttpStatusCode.InternalServerError)
            //    {
            //    }
            //};
            PutRet ret = client.PutFile(upToken, key, fname, extra);
            return ret;
        }
        /// <summary>
        /// 普通上传图片
        /// key必须采用utf8编码,如使用非utf8编码访问七牛云存储将反馈错误
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="key">上传后的路径</param>
        /// <param name="fname">要上传的文件路径(文件必须存在)</param>
        public static PutRet PutImage(string key, string fname, string mimeType = "image/jpg")
        {
            if (key.IndexOf('.') == -1) key += Path.GetExtension(fname);
            if (mimeType == "") mimeType = GetMimeTypeByExtension(Path.GetExtension(fname));
            var policy = new PutPolicy(bucket, 3600);
            string upToken = policy.Token();
            PutExtra extra = new PutExtra
            {
                MimeType = mimeType,
                Crc32 = 123,
                CheckCrc = CheckCrcType.CHECK,
                Params = new Dictionary<string, string>()
            };
            IOClient client = new IOClient();
            PutRet ret = client.PutFile(upToken, key, fname, extra);
            return ret;
        }
        /// <summary>
        /// 上传文件到网站服务器,再上传到七牛服务器
        /// </summary>
        /// <param name="fileData">页面/swf传过来的文件数据</param>
        /// <param name="fileType">预留</param>
        /// <param name="path">文件加逻辑路径,如:images/ </param>
        /// <param name="isOriginal">是否保留文件原名</param>
        /// <param name="prefix">不保留原名时,文件名的前缀部分</param>
        /// <returns></returns>
        public static PutRet UploadFile(HttpPostedFileBase fileData, string fileType = "", string path = "", string isOriginal = "",string prefix="")
        {
            PutRet ret = null;
            if (fileData != null)
            {
                var fileExt = Path.GetExtension(fileData.FileName);
                var fileName = "";
                if (isOriginal != "1")
                {
                    fileName = DataHelper.CreateRandomName(fileExt);
                    if (prefix != "") fileName = prefix + fileName;
                }
                else fileName = Path.GetFileName(fileData.FileName).Replace(" ", "");
                var fileFullPath = "";
                bool isImage = false;
                string mimeType = GetMimeTypeByExtension(fileExt);
                if (mimeType == "")
                {
                    if (path.Len() == 0) path = "files/";
                    fileFullPath = Path.Combine(path, fileType);
                }
                else if (mimeType.StartsWith("image"))
                {
                    if (path.Len() == 0) path = "images/";
                    fileFullPath = Path.Combine(path, fileType);
                    isImage = true;
                }
                else
                {
                    if (path.Len() == 0) path = "other/";
                    fileFullPath = Path.Combine(path, fileType);
                }
                if (!Directory.Exists(cdnPath + fileFullPath))
                {
                    Directory.CreateDirectory(cdnPath + fileFullPath);
                }
                var fileFullName = cdnPath + fileFullPath + "/" + fileName;
                fileData.SaveAs(fileFullName);
                string key = string.Empty;
                //上传图片到七牛
                if (System.IO.File.Exists(fileFullName))
                {
                    // long len = fileData.ContentLength / 1024;
                    key = fileFullName.Replace(cdnPath, "").Replace("\\", "/").Replace("//", "/");
                    if (isImage) ret = PutImage(key, fileFullName, mimeType);
                    else ret = PutFile(key, fileFullName);
                }
            }
            return ret;
        }
        /// <summary>
        /// 通过后缀获取mime类型
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        private static string GetMimeTypeByExtension(string extension)
        {
            string mimeType = "";
            extension = extension.TrimStart('.').ToLowerInvariant();
            switch (extension)
            {
                case "gif":
                    mimeType = "image/gif";
                    break;
                case "png":
                    mimeType = "image/png";
                    break;
                case "bmp":
                    mimeType = "image/bmp";
                    break;
                case "jpeg":
                case "jpg":
                    mimeType = "image/jpg";
                    break;
            }
            return mimeType;
        }
        /// <summary>
        /// 断点续传
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="key"></param>
        /// <param name="fname"></param>
        public static void ResumablePutFile(string bucket, string key, string fname)
        {
            Console.WriteLine("\n===> ResumablePutFile {0}:{1} fname:{2}", bucket, key, fname);
            PutPolicy policy = new PutPolicy(bucket, 3600);
            string upToken = policy.Token();
            Settings setting = new Settings();
            ResumablePutExtra extra = new ResumablePutExtra();
            // extra.Notify += PutNotifyEvent;//(int blkIdx, int blkSize, BlkputRet ret);//上传进度通知事件
            ResumablePut client = new ResumablePut(setting, extra);
            client.PutFile(upToken, fname, Guid.NewGuid().ToString());
        }
        /// <summary>
        /// 得到文件的外链地址 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="isPublic"></param>
        /// <returns></returns>
        public static string GetUrl(string key, bool isPublic = true)
        {
            string baseUrl = GetPolicy.MakeBaseUrl(Domain, key);
            if (isPublic) return baseUrl;
            string private_url = GetPolicy.MakeRequest(baseUrl);
            return private_url;
        }
        /// <summary>
        /// 获取图片信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="isPublic"></param>
        /// <returns></returns>
        public static ImageInfoRet GetImageInfo(string key, bool isPublic = true)
        {
            string url = GetPolicy.MakeBaseUrl(Domain, key);
            //生成fop_url
            string imageInfoURL = ImageInfo.MakeRequest(url);
            //对其签名,生成private_url。如果是公有bucket此步可以省略
            if (!isPublic) imageInfoURL = GetPolicy.MakeRequest(imageInfoURL);
            ImageInfoRet infoRet = ImageInfo.Call(imageInfoURL);
            if (infoRet.OK)
            {
                Console.WriteLine("Format: " + infoRet.Format);
                Console.WriteLine("Width: " + infoRet.Width);
                Console.WriteLine("Heigth: " + infoRet.Height);
                Console.WriteLine("ColorModel: " + infoRet.ColorModel);
            }
            else
            {
                Console.WriteLine("Failed to ImageInfo");
            }
            return infoRet;
        }
        public static string GetImagePreviewUrl(string key, bool isPublic = true)
        {
            string url = GetPolicy.MakeBaseUrl(Domain, key);
            ImageView imageView = new ImageView { Mode = 0, Width = 200, Height = 200, Quality = 90, Format = "jpg" };
            string viewUrl = imageView.MakeRequest(url);
            if (!isPublic) viewUrl = GetPolicy.MakeRequest(viewUrl);//私链
            return viewUrl;
        }
        /// <summary>
        /// 获取水印图片
        /// </summary>
        /// <param name="key"></param>
        /// <param name="type"></param>
        /// <param name="waterString"></param>
        /// <param name="isPublic"></param>
        /// <param name="waterColor"></param>
        /// <returns></returns>
        public static string GetWaterMarker(string key, WaterType type = WaterType.No, string waterString = "", bool isPublic = true, string waterColor = "red")
        {
            string url = GetUrl(key);
            string markerUrl = string.Empty;
            switch (type)
            {
                case WaterType.Text:
                    {
                        //文字水印
                        WaterMarker marker = new TextWaterMarker(waterString, "", waterColor);
                        markerUrl = marker.MakeRequest(url);
                    }
                    break;
                case WaterType.Image:
                    {
                        //图片水印
                        WaterMarker marker = new ImageWaterMarker(waterString);
                        markerUrl = marker.MakeRequest(url);
                    }
                    break;
            }
            if (!isPublic && !string.IsNullOrEmpty(markerUrl)) markerUrl = GetPolicy.MakeRequest(markerUrl);
            return markerUrl;
        }
        /// <summary>
        /// 水印类型枚举
        /// </summary>
        public enum WaterType
        {
            /// <summary>
            /// 无水印
            /// </summary>
            No,
            /// <summary>
            /// 文字水印
            /// </summary>
            Text,
            /// <summary>
            /// 图片水印
            /// </summary>
            Image
        }
    }
}


.Net MVC控制器调用上传:

03
2015
04

个人使用七牛云服务API作为非黄钻QQ空间播放背景音乐的用法

七牛文档中心:http://developer.qiniu.com/


我就是做了一个页面使用API上传文件,然后获取上传的文件链接用在QQ空间,说一下使用音乐的步骤。

花几分钟做了个简单的使用教程。


个人后台登陆地址:/Admin/Auth/Login

15
2015
01

.Net中模拟上传文件动态显示进度的事件示例

.Net Code:

    public class UploadEventArgs : EventArgs//作为事件的参数,必须派生自EventArgs基类
    {
        public UploadEventArgs(int percent)
        {
            this.Percent = percent;
        }
        public int Percent { get; set; }
    }
    public class Upload
    {
        public event EventHandler<UploadEventArgs> Uploading;//定义事件,上传中实时通知上传进度
        public int Percent{get;private set;}
        public Upload()
        {
            Percent = 0;
        }
        public void DoUpload()
        {
            UploadEventArgs ev=new UploadEventArgs(0);
            while(Percent<100)
            {
//上传文件代码简单,就不写出了
                System.Threading.Thread.Sleep(1000);
                Percent+=15;
                if (Percent > 100) Percent = 100;
                ev.Percent=Percent;
                Uploading(this, ev);
            }
        }
    }
    public class FileToUpload
    {
        private string fileName;
        public FileToUpload(string filename)
        {
            this.fileName = filename;
        }
        public void GetStatus(object sender, UploadEventArgs e)
        {
            Console.WriteLine("file:{0},UploadPercent:{1}", fileName, e.Percent);
        }
    }
    public class EventTest
    {
        public void test()
        {
            var upload = new Upload();
            var file = new FileToUpload("001.dox");
            upload.Uploading += file.GetStatus;
            upload.DoUpload();
        }
    }


26
2014
12

给ef6的实体模型 edmx文件加字段注释

code smith 模版(要下载code smith软件使用):

//生成注释部分代码

04
2014
08

C++MFC编程笔记day06 MFC向导、MFC绘图类使用

 MFC绘图

   MFC绘图类包括绘图设备类和绘图对象类

   1 绘图设备类

     CDC类-父类是CObject,封装的是一般的绘图设备,例如:显示器,

           打印机等。

     CWindowDC类-父类是CDC类,封装的是窗口对象,包括客户区和非

01
2014
08

标C编程笔记day06 动态分配内存、函数指针、可变长度参数

动态分配内存:头文件 stdlib.h

    malloc:分配内存

    calloc:分配内存,并清零

    realloc:调整已分配的内存块大小

    示例:

        int *p=(int *) malloc(3*sizeof(int));//分配内存,成功返回首地址,失败返回NULL

01
2014
08

标C编程笔记day05 函数声明、文件读写、联合类型、枚举类型

函数声明:

    1、隐式声明:在没有声明的情况下,系统可根据参数类型判断去调用函数(有可能出错)

    2、显式声明:声明在被调用之前,如:double add(double,double);  函数声明参数可只写类型,不需要写函数体。


文件操作:

    fopen  --打开文件,FILE *pFile=fopen("a.txt","w");

31
2014
07

标C编程笔记day04 预处理、宏定义、条件编译、makefile、结构体使用

预处理:也就是包含需要的头文件,用#include<标准头文件>或#include "自定义的头文件"


宏定义,如:#define PI 3.1415926

查看用宏定义的值替换宏名称,如:gcc -E test.c

带参数的宏:MAX(x,y) (x)>(y)?((x):(y))   //使用方法与函数一样

宏运算:

    #define PRINT(n) printf(#n"=%d",n)   //#n 就是把传入的变量值作为字符串放在那里

30
2014
07

标C编程笔记day01~day03 变量、运算符、指针、函数、输入输出

c/c++语法,运算符:

    sizeof()  --参数为变量或类型,计算变量或类型的字节大小

    a==b?c:d  --三目运算符,a==b时,返回c,否则返回d

    算术运算符:+,-,*,/,%

    自加、自减运算:++,--

    位运算:

        ~ --取反,正数取反为 -(n+1) ,负数取反为 n-1 

30
2014
07

C++MFC编程笔记day05 文档类-单文档和多文档应用程序

 文档类

   1 相关类

   CDocument类-父类是CCmdTarget类,所以,文档类也可以处理菜单等

              命令消息。作用保存和管理数据。

   注意事项:如何解决断言错误