使用上傳插件 Web Uploader 上傳圖片到七牛雲(C#)


之前有寫過一篇文章,基於asp.net mvc 封裝 Web Uploader 上傳插件:

http://www.cnblogs.com/vanteking/p/5623682.html

已經實現的功能有:

封裝 my97datepicker 日歷插件 :

 @Html.Calendar("time")

封裝 ckeditor編輯器:

 @Html.RichTextEditor("CKEDITOR1", new RichTextEditor { Height = 300, ToolBar = RichTextEditorToolBar.Full, Plugins = RichTextEditorPlugins.CKEDITOR, Width = 900 })

 

另外還有百度編輯器的封裝,只需要改版參數就可以使用了。
ckeditor 里還配合使用了 ckfinder

 

今天重點講下封裝的Web Uploader插件,圖片可以上傳到七牛雲和本地。

先上圖:

 

 

 

 

圖片上傳到七牛雲:

                //Qiniu雲
                var file = Request.Files["file"];
                if (file != null && file.InputStream != null && file.ContentLength > 0)
                {
                    //七牛空間
                    var qiniuStore = SystemConst.GetRandStore();
                    //學校
                    var school = ViewBag._school_ as SchoolLibrary;
                    //時間戳
                    var stime = TimeHelper.ConvertDateTimeInt(DateTime.Now);
                    //原始文件名
                    var mine = file.FileName.Substring(file.FileName.LastIndexOf("."));
                    //目標地址
                    var filePath = "{0}/{1}/{2}{3}".FormatWith(school.Domain, user.ID.GetHashCode(), stime, mine);
                    //模型
                    var buket = new Bucket
                    {
                        FileType = (UploadFileType)fileType,
                        stream = file.InputStream,
                        saveFilePath = filePath,
                        saveFileName = file.FileName,
                        bucket = qiniuStore.Space,
                        PicDomain = qiniuStore.Domain
                    };
                    uploadResult = BucketHelper.UploadFile(buket);

刪除七牛雲圖片:

 //人員信息
            var user = ViewBag.stu as OStudent;
            //域名空間
            var qiniuStore = SystemConst.StoreList.FirstOrDefault(m => file.IsNullOrEmpty() == false && file.StartsWith(m.Domain));

            if (string.IsNullOrEmpty(file) == true) { _msg = "文件未找到!"; }
            else if (qiniuStore != null)
            {
                if (file.ToLower().Contains(user.ID.GetHashCode().ToString()) == false) { _msg = "沒有權限!"; }
                else
                {
                    //地址
                    var saveFilePath = file.Replace(qiniuStore.Domain, "").Trim();
                    //模型
                    var buket = new Bucket
                    {
                        saveFilePath = saveFilePath,
                        bucket = qiniuStore.Space,
                    };
                    var result = BucketHelper.Delete(buket);
                    if (result.State == (int)UploadState.Success)
                    {
                        _err = false;
                    }
                    else
                    {
                        _msg = result.ErrorMessage;
                    }
                }
            }

 

還做了一個七牛雲的類的封裝:

上傳:

     /// <summary>
        /// 上傳文件
        /// </summary>
        /// <param name="model"></param>
        /// <param>FileType 文件類型</para>
        /// <param>bucket 目標空間 默認:studystone</para>
        /// <param>PicDomain 目標空間對應的默認域名 </para>
        /// <param>strSchool 學校二級</para>
        /// <param>saveFileName 目標文件名</para>
        /// <param>localFile 本地文件(優先)</para>
        /// <param>stream 文件流(本地文件存在則,忽略)</para>
        /// <returns></returns>
        public static UploadResult UploadFile(Bucket model)
        {
            //結果
            var result = new UploadResult { };
            //數據
            var data = new HttpResult();
            //類型
            switch (model.FileType)
            {
                case UploadFileType.Image:
                    model.mimeLimit = "image/*";
                    model.fsizeLimit = 2097152;//2M
                    break;
                case UploadFileType.Video:
                    model.mimeLimit = "video/mp4";
                    model.fsizeLimit = 41943040;//40M
                    break;
                case UploadFileType.File:
                default:
                    model.mimeLimit = "application/msword;application/vnd.openxmlformats-officedocument.wordprocessingml.document;application/vnd.ms-excel;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;application/pdf;application/vnd.ms-powerpoint;application/x-rar-compressed;application/x-zip-compressed;text/css;text/html;application/x-javascript;application/json;text/plain";
                    model.fsizeLimit = 41943040;//40M
                    break;
            }
            // 上傳策略
            PutPolicy putPolicy = new PutPolicy();
            // 設置要上傳的目標空間
            putPolicy.Scope = model.bucket;
            // 上傳策略的過期時間(單位:秒)
            putPolicy.SetExpires(3600);
            // 文件上傳完畢后,在多少天后自動被刪除
            //putPolicy.DeleteAfterDays = int.MaxValue;
            // Use AK & SK here
            Mac mac = new Mac(AK, SK);
            // 生成上傳憑證
            string uploadToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            // 開始上傳文件
            FormUploader um = new FormUploader();
            try
            {
                //目標地址
                if (string.IsNullOrEmpty(model.localFile) == false && File.Exists(model.localFile) == true)
                {
                    data = um.UploadFile(model.localFile, model.saveFilePath, uploadToken);
                }
                else if (model.stream != null)
                {
                    data = um.UploadStream(model.stream, model.saveFilePath, uploadToken);
                }
                else
                {
                    result.State = UploadState.Unknown;
                    result.ErrorMessage = "上傳文件為空";
                    return result;
                }
                //結果判斷
                switch (data.Code)
                {
                    //上傳成功
                    case 200:
                        result.file = new QiniuFile
                        {
                            Date = DateTime.Now.ToString("yyyy年MM月dd日"),
                            Moment = DateTime.Now.ToString("HH:mm tt").Replace("上午", "AM").Replace("下午", "PM"),
                            FileName = model.saveFilePath.Substring(model.saveFilePath.LastIndexOf("/") + 1),
                            Fsize = 0,
                            Src = model.PicDomain + model.saveFilePath
                        };
                        result.State = UploadState.Success;
                        result.Url = model.PicDomain + model.saveFilePath;
                        result.OriginFileName = model.saveFilePath.Substring(model.saveFilePath.LastIndexOf("/") + 1);
                        break;
                    case 403:
                        result.State = UploadState.TypeNotAllow;
                        result.ErrorMessage = "不允許的文件格式上傳";
                        break;
                    case 413:
                        result.State = UploadState.TypeNotAllow;
                        result.ErrorMessage = "文件大小超過限制";
                        break;
                    case 612:
                        result.State = UploadState.TypeNotAllow;
                        result.ErrorMessage = "文件已存在";
                        break;
                    default:
                        result.State = UploadState.Unknown;
                        result.ErrorMessage = "文件上傳失敗";
                        break;
                }
            }
            catch (Exception e)
            {
                result.State = UploadState.Unknown;
                result.ErrorMessage = e.Message;
            }
            return result;
        }

獲取七牛雲圖片列表

   /// <summary>
        /// 獲取空間下面所有的圖片
        /// </summary>
        /// <param name="model"></param>
        /// <para>bucket 目標空間默認:stonestudy</para>
        /// <para>prefix 按文件名前綴保留搜索結果 如:ss/</para>
        /// <para>limit  每次最大請求的數量最大1000</para>
        /// <para>delimiter</para>
        /// <returns></returns>
        public static List<QiniuFile> FileList(Bucket model)
        {
            Mac mac = new Mac(AK, SK);
            BucketManager bm = new BucketManager(mac);

            // 返回結果存儲在items中
            List<QiniuFile> items = new List<QiniuFile>();
            // 由於limit限制,可能需要執行多次操作
            // 返回值中Marker字段若非空,則表示文件數超過了limit
            do
            {
                var result = bm.ListFiles(model.bucket, model.prefix, model.marker, model.limit, model.delimiter);
                //標記
                model.marker = result.Result.Marker;
                if (result.Result.Items != null)
                {
                    result.Result.Items.ForEach(m =>
                    {
                        var date = TimeHelper.GetFullTime(m.PutTime.ToString());
                        items.Add(new QiniuFile
                        {
                            FileName = m.Key.Substring(m.Key.LastIndexOf("/") + 1),
                            Fsize = m.Fsize,
                            MimeType = m.MimeType,
                            Src = model.PicDomain + m.Key,
                            Date = date.ToString("yyyy年MM月dd日"),
                            Moment = date.ToString("HH:mm tt").Replace("上午", "AM").Replace("下午", "PM")
                        });
                    });
                }
            } while (!string.IsNullOrEmpty(model.marker));
            return items;
        }

 

刪除圖片

 /// <summary>
        /// 刪除文件
        /// </summary>
        /// <param name="model"></param>
        /// <para>bucket 目標空間 默認:studystone</para>
        /// <para>saveFilePath 目標文件,非全路徑 例如: temp/logo.png</para>
        /// <returns></returns>
        public static UploadResult Delete(Bucket model)
        {
            var result = new UploadResult();
            try
            {
                Mac mac = new Mac(AK, SK);
                BucketManager target = new BucketManager(mac);
                var data = target.Delete(model.bucket, model.saveFilePath);
                switch (data.Code)
                {
                    //上傳成功
                    case 200:
                        result.State = UploadState.Success;
                        break;
                    case 612:
                        result.State = UploadState.TypeNotAllow;
                        result.ErrorMessage = "    待刪除資源不存在";
                        break;
                    default:
                        result.State = UploadState.Unknown;
                        result.ErrorMessage = "文件刪除失敗";
                        break;
                }
            }
            catch (Exception)
            {
                result.State = UploadState.Unknown;
                result.ErrorMessage = "文件刪除失敗";
            }
            return result;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM