C#对七牛云的操作

1.布置环境

项目中引用 QiNiu.4.0.dll

在webconfig:
<add key=”USER_AGENT” value=”qiniu csharp-sdk v6.0.0″/>
<add key=”ACCESS_KEY” value=””/>//账号 —> 密钥AK
<add key=”SECRET_KEY” value=””/>//账号 —> 密钥SK
<add key=”RS_HOST” value=”http://rs.Qbox.me"/&gt;
<add key=”UP_HOST” value=”http://up.qiniu.com"/&gt;
<add key=”RSF_HOST” value=”http://rsf.Qbox.me"/&gt;
<add key=”PREFETCH_HOST” value=”http://iovip.qbox.me"/&gt;
<add key=”API_HOST” value=”http://api.qiniu.com"/&gt;

2.创建七牛文件的实体类
  public class QiNiuFile{
            public string fileUrl { get; set; }
            public string fileKey { get; set; }
            public string fileMime { get; set; }
            public string fileThumbnailUrl { get; set; }
        }

3.页 面Html 用的form 提交
<style type=”text/css”>
    .c-list {
        color: #000;
        margin: 0 0 0 10px;
    }

    .text-none {
        display: none;
    }

    .text-block {
        display: block;
    }

    .td1 {
        background-color: Silver;
    }

    .inputFile
    {
        display:none;
    }

    .opacity
    {
        filter:alpha(opacity=50); /*IE滤镜,透明度50%*/
        -moz-opacity:0.5; /*Firefox私有,透明度50%*/
        opacity:0.5; /*其他,透明度50%*/
    }

    #fileList .file
    {
        margin: 10px;
        width: 80px;
        height: 80px;
        float: left;
    }

     #fileList .file div
    {
       margin-left: auto;
       margin-right: auto;
    }

    #fileList .file .flieKey
    {
        width: 60px;
        height: 60px;
    }

     #fileList .file .flieKey img
    {
        width: 60px;
        height: 60px;
    }

     #fileList .file .fileName
    {
       text-align: center;
    }

    #loadSta
    {
        position:absolute;
        left:0px;
        top:0px;
        width:100%;
        height:100px;
        z-index:99;
        filter:alpha(opacity=50);
        vertical-align:middle;
        text-align:center;
        display:none;
    }
        #loadSta img
        {
            margin-top:200px;
        }

</style>
<form id=”filePost” action=””(填写Url) method=”post”
enctype=”multipart/form-data”>
            <input type=”file” name=”file” class=”inputFile”/>
            <a class=”btn-25 c-red mr10″ data-act =
“chooseFile”>选取文件</a>
            <a class=”btn-25 c-red mr10″ data-act =
“uploadFile”>上传文件</a>
            <a class=”btn-25 c-red mr10″ data-act =
“seeFile”>查看</a>
            <a class=”btn-25 c-red mr10″ data-act =
“downLoadFile”>下载</a>
            <a class=”btn-25 c-red mr10″ data-act =
“deleteFile”>删除</a>
            <a class=”btn-25 c-red mr10″ data-act =
“pushFile”>推送</a>
</form>
<div id =”fileList”></div>@* 加载七牛云的数据 *@
<div id=”loadSta” > @* 上传的功用*@
       <img src=”~/Images/uploadfile.gif” />
</div>

4.JS

$(document).ready(function () {
    UploadPushManageMgr.InitPageEvEnt();
    UploadPushManageMgr.InitPageData();
});

var UploadPushManageMgr = {
    fileName : ”,

    InitPageEvEnt: function () {
        $(‘#filePost a[data-act=chooseFile]’).on(‘click’, function ()
{
            $(‘#filePost .inputFile’).click();
        });

        $(‘#filePost a[data-act=uploadFile]’).on(‘click’, function ()
{
             $(“#loadSta”).css(‘display’,’block’);

            $(‘#filePost’).ajaxSubmit({
                success: function (result) {
                    $(“#loadSta”).css(‘display’, ‘none’);
                    alert(result);
                    UploadPushManageMgr.InitPageData();
                },
                error: function (ex) {
                    //alert(ex.responseText);
                }
            });
        });

        $(“#fileList .file”).live(‘click’, function () {
            UploadPushManageMgr.fileName = $(this).attr(‘name’);
            $(this).siblings().addClass(‘opacity’);
            $(this).removeClass(‘opacity’);
        });

        $(‘#filePost a[data-act=seeFile]’).on(‘click’, function ()
{
            var dataCarrier = new Object();
            dataCarrier.fileName = UploadPushManageMgr.fileName;
            if (dataCarrier.fileName != 0) {
                $.ajax({
                    type: “POST”,
                    url:
“/GouGouCloudManage/UploadPushManage/SeeFile”,
                    data: JSON.stringify(dataCarrier),
                    dataType: “json”,
                    contentType: “application/json;charset=utf-8”,
                    success: function (result) {
                        window.open(result, ”,
‘width=500,height=500’);
                    },
                    error: function (ex) {
                        //alert(ex.responseText);
                    }
                });
            } else {
                alert(“请选用要查阅的文书!!!”);
            }
        });

        $(‘#filePost a[data-act=downLoadFile]’).on(‘click’, function
() {
            var dataCarrier = new Object();
            dataCarrier.fileName = UploadPushManageMgr.fileName;

            try {
                var Message =
“\u8bf7\u9009\u62e9\u6587\u4ef6\u5939”; //采取框提醒音信
                var Shell = new ActiveXObject(“Shell.Application”);
                var Folder = Shell.BrowseForFolder(0, Message, 64, 17);
//起头目录为:笔者的总计机
                if (Folder != null) {
                    Folder = Folder.items(); // 返回 FolderItems 对象
                    Folder = Folder.item(); // 返回 Folderitem 对象
                    Folder = Folder.帕特h; // 重回路径
                    if (Folder.charAt(Folder.length – 1) != “\\”) {
                        Folder = Folder + “\\”;
                    }
                    dataCarrier.filePath = Folder;
                }
            }
            catch (e) {
                alert(e.message);
            }

            if (dataCarrier.fileName != ” && dataCarrier.filePath !=
”) {
                $.ajax({
                    type: “POST”,
                    url:
“/GouGouCloudManage/UploadPushManage/DownLoadFile”,
                    data: JSON.stringify(dataCarrier),
                    dataType: “json”,
                    contentType: “application/json;charset=utf-8”,
                    success: function (result) {
                        alert(result);
                    },
                    error: function (ex) {
                        //alert(ex.responseText);
                        alert(‘//即便提醒权限不够
在浏览器中设置一下有惊无险难题 //Internet选项 》 安全 》 受注重的站点 》站点
》 添加当前网站//Internet选项 》 安全 》 自定义级别
》对标记为可无恙实施脚本的ActiveX控件执行脚本* 》 启用’);
                    }
                });
            } else {
                alert(“请接纳要下载的公文!!!”);
            }
        });

        $(‘#filePost a[data-act=deleteFile]’).on(‘click’, function ()
{
            var dataCarrier = new Object();
            dataCarrier.fileName = UploadPushManageMgr.fileName;
            if (dataCarrier.fileName != “”) {
            var state = confirm(“你规定要刨除该公文呢?”);
            if (state) {
                    $.ajax({
                        type: “POST”,
                        url:
“/GouGouCloudManage/UploadPushManage/DeleteFile”,
                        data: JSON.stringify(dataCarrier),
                        dataType: “json”,
                        contentType: “application/json;charset=utf-8”,
                        success: function (result) {
                            if (result == ‘OK’) {
                                alert(“删除成功”);
                                UploadPushManageMgr.InitPageData();

                            } else {
                                alert(“删除失利”);
                            }
                        },
                        error: function (ex) {
                            //alert(ex.responseText);
                        }
                    });
                }

            } else {
                alert(“请选取你要去除的文书!!!”);
            }
        });

        $(‘#filePost a[data-act=pushFile]’).on(‘click’, function ()
{

            var dataCarrier = new Object();
            dataCarrier.fileName = UploadPushManageMgr.fileName;
            if (dataCarrier.fileName != ”) {
                var state = confirm(“你规定要推送该文件呢?”);
                if (state) {
                    $.ajax({
                        url:
“/GouGouCloudManage/UploadPushManage/PushFile”,
                        type: “POST”,
                        data: JSON.stringify(dataCarrier),
                        dataType: “json”,
                        contentType: “application/json;charset=utf-8”,
                        success: function (result) {
                            alert(result);
                            //if (result == ‘OK’) {
                            //    alert(“推送成功”);
                            //} else {
                            //    alert(“删除退步”);
                            //}
                        },
                        error: function (ex) {
                            //alert(ex.responseText);
                        }
                    });
                }
            } else {
                alert(“请接纳要推送的文本!!!”);
            }
        })
    },

    InitPageData: function () {
        var dataCarrier = new Object();
        $.ajax({
            type: “POST”,
            url: “/GouGouCloudManage/UploadPushManage/InitPageDate”,
            data: JSON.stringify(dataCarrier),
            dataType: “json”,
            contentType: “application/json;charset=utf-8”,
            success: function (result) {
                var fileHtml = “”;
                for (var i = 0; i < result.length; i++) {
                    if (result[i].fileMime.indexOf(“video”) == -1) {
                        fileHtml += “<div class = ‘file opacity’ name
= ” + result[i].fileKey + “><div class = ‘flieKey’><img
src=” + result[i].fileUrl + “></div><div class =
‘fileName’>” + result[i].fileKey + “</div></div>”;
                    } else {
                        fileHtml += “<div class = ‘file opacity’ name
= ” + result[i].fileKey + “><div class = ‘flieKey’><img
src=” + result[i].fileThumbnailUrl + “></div><div class =
‘fileName’>” + result[i].fileKey + “</div></div>”;
                    }
                }
                $(“#fileList”).html(fileHtml);
            },
            error: function (ex) {
                //alert(ex.responseText);
            }
        });
    }
};

5.Controller:

 public class UploadPushManageController : BaseController
    {
        IDeviceManage DevManage = new DeviceManage();
        User user = new User();
        MonitorManage momange = new MonitorManage();
        icm_usercloud usercload = new icm_usercloud();

        /// <summary>
        /// 页面加载
        /// </summary>
        /// <returns></returns>
        public ActionResult ExplorerView()
        {
            // ViewBag.ftp = Request[“ftp”] == null ? “” :
Request[“ftp”];

            icm_usercloud usercloud =
momange.GetUserCloudByUserID(user.Uid);
            ViewBag.Size = usercload.SIZE;
            QiNiuHelper.InitQiniu();
            return View();
        }

        #region New 20151230 wyh

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name=”domain”>
用户七牛的半空中[未来私下认可]</param>
        /// <returns></returns>
        public ActionResult UploadFile(string domain)
        {
            bool isFull = true; //判断用户空间是不是已满
            JsonResult result = new JsonResult();
            var file = Request.Files[“file”];
            if (Request.Files.Count == 0)
            {
                result.Data = “无法上传空文件”;
            }
            else
            {
                if (file.ContentLength > 2097152000)
                {
                    return new JsonResult { Data = “文件超出最大限度”
};
                }

                //给用户在多少中添加记录
                //usercload.PID = user.PID;
                //usercload.UID = user.Uid;
                //usercload.SIZE = file.ContentLength;
                //icm_usercloud usercloudOld =
momange.GetUserCloudByUserID(user.Uid);

                if (usercloudOld != null)
                {
                    if (usercloudOld.SIZE > 2048000 –
usercloudOld.SIZE)
                    {
                        return new JsonResult { Data =
“该用户空间欠缺!!!” };
                    }
                    else
                    {
                        isFull = false;
                        //修改数据中用户的剩下空间
                        //usercload.SIZE = usercloudOld.SIZE +
usercload.SIZE;
                        //usercload.UT = DateTime.Now;
                        //momange.UpdateUserCloudByUserID(usercload);
                    }
                }
                else
                {
                    if (file.ContentLength > 2097152000)
                    {
                        return new JsonResult { Data =
“该文件已高于上传最大限度!!!” };
                    }
                    else
                    {
                        isFull = false;
                        //在数据库中开创用户
                        //momange.InsertUserCloud(usercload);
                    }
                }

                if (!isFull)
                {
                    bool statis = QiNiuHelper.PutFile(file.FileName,
file.InputStream, domain);
                    if (statis)
                    {
                        result.Data = “上传成功”;
                    }
                    else
                    {
                        result.Data = “上传退步”;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 加载用户在七牛全数文件
        /// </summary>
        /// <param
name=”qiNiuDomain”>用户在七牛的半空中</param>
        /// <returns></returns>
        public ActionResult InitPageDate(string qiNiuDomain = null)
        {
            Qiniu.Conf.Config.Init();
            JsonResult result = new JsonResult();
            List<DumpItem> qiniufileList =
QiNiuHelper.ListFile(qiNiuDomain);
            List<QiNiuFile> fileList = new
List<QiNiuFile>();
            foreach (DumpItem item in qiniufileList)
            {
                QiNiuFile file = new QiNiuFile();
                file.fileMime = item.Mime;
                file.fileUrl = QiNiuHelper.GetFileUrl(item.Key, false,
qiNiuDomain);
                file.fileKey = item.Key;
                if (item.Mime.Contains(“video”))
                {
                    file.fileThumbnailUrl =
QiNiuHelper.ThumbnailUrl(file.fileKey);
                }
                fileList.Add(file);
            }
            result.Data = fileList;
            return result;
        }

        /// <summary>
        /// 查看文件
        /// </summary>
        /// <param name=”fileName”>文件名</param>
        /// <returns></returns>
        public ActionResult SeeFile(string fileName, string qiNiuDomain
= null)
        {
            string fileUrl = QiNiuHelper.GetFileUrl(fileName, true,
qiNiuDomain);
            return new JsonResult()
            {
                Data = fileUrl
            };
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name=”fileName”></param>
        /// <param name=”filePath”>下载到的地方</param>
        /// <returns></returns>
        public ActionResult DownLoadFile(string fileName, string
filePath, string qiNiuDomain = null)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return new JsonResult { Data = “无下载路径!!!” };
            }

            JsonResult result = new JsonResult();
            string remoteUri = QiNiuHelper.GetFileUrl(fileName, false,
qiNiuDomain);
            string myStringWebResource = null;
            WebClient myWebClient = new WebClient();
            myStringWebResource = remoteUri + fileName;
            string receivePath = filePath;
            myWebClient.DownloadFile(myStringWebResource, receivePath +
fileName);

            result.Data = “下载成功”;
            return result;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name=”fileName”></param>
        /// <param name=”qiNiuDomain”></param>
        /// <returns></returns>
        public ActionResult DeleteFile(string fileName, string
qiNiuDomain = null)
        {
            JsonResult result = new JsonResult();
            bool statis = QiNiuHelper.Delete(fileName, qiNiuDomain);
            if (statis)
            {
                result.Data = “OK”;
            }
            return result;
        }

        /// <summary>
        /// 推送文件
        /// </summary>
        /// <param name=”fileName”>文件名</param>
        /// <param name=”domainUrl”></param>
        /// <returns></returns>
        public ActionResult PushFile(string fileName, string domainUrl =
null)
        {
            //推送的Url
            string fileUrl = QiNiuHelper.GetFileUrl(fileName, true,
domainUrl);
            icm_usercloud usercloud =
momange.GetUserCloudByUserID(user.Uid);
            //user.Uid;//用户ID
            //usercload.SIZE; //用户的长空

            return new JsonResult()
            {
                Data = fileUrl + “-” + user.Uid + “-” + usercload.SIZE
            };
        }

6.QiNiuHelper:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using Qiniu.IO;
using Qiniu.RPC;
using Qiniu.RS;
using Qiniu.RSF;
using Qiniu.IO.Resumable;

namespace ICloudMonitorWebApp.Common.Util
{
    public class QiNiuHelper
    {

        //暗许空间
        public const string qiNiuDomain = “dfdf”;
        //七牛域名仅供测试使用,推荐绑定自定义域名取得更好的效益。
[暗中同意七牛域名]
        public const string qiNiuDomainUrl =
“7xph6u.com1.z0.glb.clouddn.com”;

        /// <summary>
        /// 上传本三步跳件到七牛[一般说来上传]
        /// </summary>
        /// <param name=”key”>文件名</param>
        /// <param name=”stream”>文件流</param>
        /// <param name=”domain”>用户的七牛空间</param>
        /// <returns></returns>
        public static bool PutFile(string key, Stream stream, string
domain = null)
        {
            if (domain == null)
            {
                domain = QiNiuHelper.qiNiuDomain;
            }
            PutPolicy policy = new PutPolicy(domain, 3600);
            string upToken = policy.Token();
            PutExtra extra = new PutExtra();
            IOClient client = new IOClient();
            PutRet ret = client.Put(upToken, key, stream, extra);
            if (ret.OK)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 断点续传
        /// </summary>
        /// <param name=”domain”>用户的七牛空间</param>
        /// <param name=”key”>文件key</param>
        /// <param name=”fname”></param>
        ///
能够通过注册ResumablePutExtra以下八个事件监听当前上传进程以及成功景色:
        public event EventHandler<PutNotifyEvent> Notify;
        public event EventHandler<PutNotifyErrorEvent>
NotifyErr;

        public static void ResumablePutFile(string domain, string key,
string fname = null)
        {
            PutPolicy policy = new PutPolicy(domain, 3600);
            string upToken = policy.Token();
            Settings setting = new Settings();
            ResumablePutExtra extra = new ResumablePutExtra();
            // extra.Notify += PutNotify伊芙nt;//(int blkIdx, int
blkSize, BlkputRet ret);//上传进程通报事件
            ResumablePut client = new ResumablePut(setting, extra);
            client.PutFile(upToken, key, Guid.NewGuid().ToString());
        }

        /// <summary>
        /// 列出全数文件消息
        /// </summary>
        /// <param name=”qiNiuDomain”>用户七牛空间</param>
        public static List<DumpItem> ListFile(string
qiNiuDomain)
        {
            if (string.IsNullOrEmpty(qiNiuDomain))
            {
                qiNiuDomain = QiNiuHelper.qiNiuDomain;
            }

            RSFClient rsf = new RSFClient(qiNiuDomain);
            rsf.Limit = int.MaxValue;
            List<DumpItem> list = new List<DumpItem>();
            List<DumpItem> items;
            while ((items = rsf.Next()) != null)
            {
                list.AddRange(items);
            }
            return list;
        }

        /// <summary>
        /// 获得文件的地点{可用于下载,查看}
        /// </summary>
        /// <param name=”key”>文件名</param>
        /// <param name=”isPublic”>私有/公开</param>
        /// <param name=”domainUrl”>空间</param>
        public static string GetFileUrl(string key, bool isPublic =
false, string domainUrl = null)
        {
            if (string.IsNullOrEmpty(domainUrl))
            {
                domainUrl = QiNiuHelper.qiNiuDomainUrl;
            }

            //公有链接
            string baseUrl = GetPolicy.MakeBaseUrl(domainUrl, key);
            if (isPublic) return baseUrl;
            //私有链接
            string private_url = GetPolicy.MakeRequest(baseUrl);
            return private_url;
        }

        /// <summary>
        /// 删除单个文件
        /// </summary>
        /// <param name=”key”>文件名</param>
        /// <param
name=”domain”>文件所在用户的上空名</param>
        public static bool Delete(string key, string qiNiuDomain =
null)
        {
            if (string.IsNullOrEmpty(qiNiuDomain))
            {
                qiNiuDomain = QiNiuHelper.qiNiuDomain;
            }
            RSClient client = new RSClient();
            CallRet ret = client.Delete(new EntryPath(qiNiuDomain,
key));
            if (ret.OK)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        ///  视屏缩略图
        /// </summary>
        /// <param name=”fileKey”>视频名</param>
        /// <param
name=”vframe”>输出的目的截图格式,支持jpg、png</param>
        /// <param
name=”offset”>钦点截取录像的每6日,单位:秒,精确到皮秒。</param>
        /// <param
name=”width”>缩略图宽度,单位:像素(px),取值范围为1-3840。</param>
        /// <param
name=”height”>缩略图中度,单位:像素(px),取值范围为1-2160。</param>
        /// <param
name=”rotate”>钦定顺时针旋转的度数,可取值为90、180、270、auto,默许为不旋转。</param>
//默许不旋转[能够采纳]
        /// <returns></returns>
        public static string ThumbnailUrl(string fileKey, string vframe
= null, string offset = null, string width = null, string height = null,
string domain = null)
        {
            //默认
            string thumbnail = “?vframe/jpg/offset/1/w/60/h/60”;

            //能够使用传参数的方式
            //string thumbnail =
string.Format(“?vframe/{0}/offset/{1}/w/{2}/h{3}”,vframe,offset,width,height);

            string ThumbnailUrl = GetFileUrl(fileKey, true, domain) +
thumbnail;
            return ThumbnailUrl;
        }

        /// <summary>
        /// 起先化七牛,读取webconfig
        /// </summary>
        public static void InitQiniu()
        {
            Qiniu.Conf.Config.Init();
        }

    }
}

相关文章