zoukankan      html  css  js  c++  java
  • Aliyun-Code-Helper:OssHelper.cs

    ylbtech-Aliyun-Code-Helper:OssHelper.cs
    1.返回顶部
    1、
    using Aliyun.OSS;
    using System;
    using System.Configuration;
    using System.IO;
    
    namespace Sp.Common
    {
        /// <summary>
        /// 阿里云OSS帮助类
        /// </summary>
        public static class OssHelper
        {
            public static readonly string AttachmentFolder = "Attachment";  //附件文件夹名称
            #region OSS 参数
            public static readonly string Endpoint = ConfigurationManager.AppSettings["OSS_Endpoint"];
            public static readonly string AccessKeyId = ConfigurationManager.AppSettings["OSS_AccessKeyId"];
            public static readonly string BucketName = ConfigurationManager.AppSettings["OSS_BucketName"];
            public static readonly string AccessKeySecret = ConfigurationManager.AppSettings["OSS_AccessKeySecret"];
            #endregion
    
            static OssClient client = new OssClient(Endpoint, AccessKeyId, AccessKeySecret);
    
            /// <summary>
            /// 上传文件
            /// </summary>
            /// <param name="key"></param>
            /// <param name="filename"></param>
            public static void PutObject(string key, string filename)
            {
                client.PutObject(BucketName, key, filename);
            }
    
            /// <summary>
            /// 上传文件
            /// </summary>
            /// <param name="key"></param>
            /// <param name="filename"></param>
            public static void PutObject(string key, Stream stream)
            {
                client.PutObject(BucketName, key, stream);
            }
    
            /// <summary>
            /// 删除文件
            /// </summary>
            /// <param name="key"></param>
            public static void DeleteObject(string key)
            {
                if (client.DoesObjectExist(BucketName, key))
                    client.DeleteObject(BucketName, key);
            }        
    
            /// <summary>
            /// 下载文件
            /// 根据key获取文件,并保存本地;临时文件,文件下载后即删除
            /// </summary>
            /// <param name="key"></param>
            /// <param name="filename"></param>
            public static void GetObject(string key, string filename)
            {
                var result = client.GetObject(BucketName, key);
                using (var requestStream = result.Content)
                {
                    using (var fs = File.Open(filename, FileMode.OpenOrCreate))
                    {
                        int length = 4 * 1024;
                        var buf = new byte[length];
                        do
                        {
                            length = requestStream.Read(buf, 0, length);
                            fs.Write(buf, 0, length);
                        } while (length != 0);
                    }
                }
            }
            
            /// <summary>
            /// 判断文件是否存在
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public static bool DoesObjectExist(string key)
            {
                return client.DoesObjectExist(BucketName, key);
            }
    
            /// <summary>
            /// 获取key
            /// </summary>
            /// <param name="extension">文件扩展名</param>
            /// <returns></returns>
            public static string GetKey(string extension)
            {
                return string.Format("{0}/{1}/{2}{3}", AttachmentFolder, DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid().ToString(), extension);
            }
        }
    }
    OssHelper.cs
    2、
    2. PutObject/上传文件返回顶部
    1、一般处理程序
    using System;
    using System.IO;
    using System.Web;
    using Sp.Common;
    using System.Text;
    
    namespace Sp.Web.Common
    {
        /// <summary>
        /// 阿里云OSS文件上传 的摘要说明
        /// </summary>
        public class FORMFileUploadAnnex : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                var postedFile = context.Request.Files["fileAttachment"];
                if (postedFile == null || postedFile.ContentLength <= 0)
                    throw new Exception("附件上传错误!");
                if (postedFile.ContentLength > 3 * 1024 * 1024)
                {
                    throw new Exception("附件大小超出限制!");
                }
    
                #region 把上传文件转换成stream
                byte[] bytes = null;
                bytes = new byte[postedFile.ContentLength];
                postedFile.InputStream.Read(bytes, 0, postedFile.ContentLength - 1);
                Stream stream = new MemoryStream(bytes);
                #endregion
    
                string key = OssHelper.GetKey(fi.Extension);
                OssHelper.PutObject(key, stream);
    
                docModel.DOC_PATH = key;
                //执行附件表数据保存操作
                var fileManager = new PUB_DOCUMENTDAO();
                fileManager.Save(docModel);
                context.Response.Clear();
                context.Response.End();
                context.Response.Close();
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
    
        }
    }
    2、
    3. GetObject/下载文件返回顶部
    1、
    using System;
    using Sp.Common;
    using System.IO;
    using System.Text;
    using System.Web;
    
    namespace Sp.Web.Common
    {
        /// <summary>
        /// 阿里云OSS文件下载 的摘要说明
        /// </summary>
        public class DownloadFile : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                string _filename = HttpUtility.UrlDecode(context.Request.QueryString["filename"], Encoding.UTF8);
                string key = HttpUtility.UrlDecode(context.Request.QueryString["key"], Encoding.UTF8);
                
                if (OssHelper.DoesObjectExist(key))
                {
                    #region 创建临时文件夹
                    var fileSavePath =  @"C:	mb_temp";
                    if (!Directory.Exists(fileSavePath))//文件夹不存在则创建
                    {
                        Directory.CreateDirectory(fileSavePath);
                    }
                    var fileFullPath = fileSavePath + @"" + _filename;//文件保存绝对路径
                    #endregion
                    FileInfo file = new FileInfo(fileFullPath);
                    if (!Directory.Exists(file.DirectoryName))
                        Directory.CreateDirectory(file.DirectoryName);
    
                    string filename = fileFullPath;
                    OssHelper.GetObject(key, filename);
    
                    //以字符流的形式下载文件
                    FileStream fs = new FileStream(filename, FileMode.Open);
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    if (File.Exists(filename))
                        File.Delete(filename);  //删除临时文件
                    context.Response.ContentType = "application/octet-stream";
                    //通知浏览器下载文件而不是打开
                    context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_filename, System.Text.Encoding.UTF8));
                    context.Response.BinaryWrite(bytes);
                    context.Response.Flush();
                    context.Response.End();
                }else
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("下载文件不存在");
                }
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    2、
    4.返回顶部
     
    5.返回顶部
     
     
    6.返回顶部
     
    warn 作者:ylbtech
    出处:http://ylbtech.cnblogs.com/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    github误fork后删除
    初识javascript
    struts验证框架失效
    Java基础学习1Java标识符及基本类型
    dos 命令行方式下启动和停止MySql服务
    html
    给文本框添加边框的两种方法
    银行家算法
    解决MyEclipse里Tomcat端口被占用而无法启动的情况
    Java近似圆
  • 原文地址:https://www.cnblogs.com/storebook/p/12659915.html
Copyright © 2011-2022 走看看