• 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"/>
    <add key="UP_HOST" value="http://up.qiniu.com"/>
    <add key="RSF_HOST" value="http://rsf.Qbox.me"/>
    <add key="PREFETCH_HOST" value="http://iovip.qbox.me"/>
    <add key="API_HOST" value="http://api.qiniu.com"/>

    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;
            80px;
            height: 80px;
            float: left;
        }

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

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

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

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

        #loadSta
        {
            position:absolute;
            left:0px;
            top:0px;
            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 = "u8bf7u9009u62e9u6587u4ef6u5939"; //选择框提示信息
                    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.Path; // 返回路径
                        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 += PutNotifyEvent;//(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">指定截取视频的时刻,单位:秒,精确到毫秒。</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();
            }

        }
    }

  • 相关阅读:
    创建pycharm项目时项目解释器的选择
    chrome插件网站
    在chrome中屏蔽百度推荐
    annotation使用示例
    scala编程第16章学习笔记(3)——List类的高阶方法
    Eclipse常用快捷键
    Ubuntu常用命令
    scala编程第16章学习笔记(2)
    scala编程第16章学习笔记(1)
    scala编程第15章
  • 原文地址:https://www.cnblogs.com/yuhangwang/p/5126682.html
Copyright © 2020-2023  润新知