上传文件到本地操作和上传到Azure云上

上传到Azure中需要引用
在这里插入图片描述

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Drawing;
using System.IO;
using System.Web;

namespace WEBAPI.Common
{
    public class FileBll
    {
        private static string _blobKey =@"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};EndpointSuffix=core.windows.net";//Blob Key


        #region 上传到本地

        /// <summary>
        /// Excel文件導出目錄
        /// </summary>
        public const string ExcelAbsolutePath = "\\Temp\\";

        /// <summary>
        /// 獲取Excel導出文件夾路徑
        /// </summary>
        /// <returns>Excel導出文件夾路徑</returns>
        public static string GetExcelExportFolderPath()
        {
            return ConfigHelper.GetAppSetting("RootPath") + ExcelAbsolutePath;
        }

        /// <summary>
        /// 獲取加上時間后的文件名
        /// </summary>
        /// <param name="name">名稱</param>
        /// <param name="extension">後綴</param>
        /// <returns>文件名</returns>
        public static string GetFileNameAppendDataTime(string name, string extension)
        {
            return string.Concat(name, DateTime.Now.ToString("yyyyMMdd_HHmmss"), ".", extension);
        }

        /// <summary>
        /// 獲取隨機文件名
        /// </summary>
        /// <param name="extension">文件後綴</param>
        /// <returns>隨機文件名</returns>
        public static string GetRandomFileName(string extension)
        {
            return string.Concat(Guid.NewGuid().ToString().Replace("-", ""), ".", extension);
        }

        /// <summary>
        /// 将Base64字符串转换为Image对象
        /// </summary>
        /// <param name="base64Str">base64字符串</param>
        /// <returns></returns>
        public static Bitmap Base64StrToImage(string base64Str)
        {
            Bitmap bitmap = null;

            try
            {
                byte[] arr = Convert.FromBase64String(base64Str);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                ms.Close();
                bitmap = bmp;
            }
            catch (Exception ex)
            {
                LogManager2.InfoFormat("保存图片失败FromBase64String:{0}", ex.Message);
            }

            return bitmap;
        }

        /// <summary>
        /// 将Base64字符串转换为图片并保存到本地
        /// </summary>
        /// <param name="base64Str">字符串的第一部分"data:image/png;base64" 是代表该Base64字符串对应的原始类型,第二部分是该文件生成的内容</param>
        /// <param name="savePath">图片保存地址,如:/Content/Images/10000.png</param>
        /// <returns></returns>
        public static string Base64StrToImage(string base64Str, string suffix, string savePath)
        {
            var fileName = "";
            try
            {
                string[] img_array = base64Str.Split(',');
                var bitmap = Base64StrToImage(img_array[1]);
                if (bitmap != null)
                {
                    //这里复制一份对图像进行保存,否则会出现“GDI+ 中发生一般性错误”的错误提示
                    var bmpNew = new Bitmap(bitmap);

                    //判断文件夹是否存在,不存在新建
                    if (!Directory.Exists(savePath))
                    {
                        Directory.CreateDirectory(savePath);
                    }

                    fileName = Guid.NewGuid() + "." + suffix;

                    bmpNew.Save(savePath + "\\" + fileName);
                    bmpNew.Dispose();
                    bitmap.Dispose();
                }
            }
            catch (Exception ex)
            {
                LogManager2.InfoFormat("保存图片失败:{0}", ex.Message);
            }

            return fileName;
        }

        #endregion 上传到本地

        #region 上传到微软云

        private string GetRandomString()
        {
            var dateNowStr = $"{DateTime.Now:yyyyMMddHHmmssfff}";
            Random rnd = new Random(Guid.NewGuid().GetHashCode());
            return $"{dateNowStr}{rnd.Next(0, 100).ToString().PadLeft(2, '0')}";
        }

        public void DeleteFile(string fileName)
        {
            DelBlob(fileName);
            //var filePath = $"{HttpContext.Current.Server.MapPath("~/")}Upload\\{fileName}";
            //if (System.IO.File.Exists(filePath))
            //{
            //    System.IO.File.Delete(filePath);
            //}
        }

        /// <summary>
        ///上传到微软云上面
        /// </summary>
        /// <param name="base64Str">文件编码</param>
        /// <param name="suffix">后缀名 jpg</param>
        /// <param name="savePath">保存地址</param>
        /// <param name="azureAccountKey">AzureKey</param>
        /// <param name="azureAccountName">AzureName</param>
        /// <returns></returns>
        public static string UploadAzureFile(string base64Str, string suffix, string savePath, string azureAccountKey, string azureAccountName)
        {
            var fileName = Guid.NewGuid() + "." + suffix;

            string[] img_array = base64Str.Split(',');
            byte[] byteArray = Convert.FromBase64String(img_array[1]);

            //HTTP Context to get access to the submitted data
            HttpContext postedContext = HttpContext.Current;
            //File Collection that was submitted with posted data
            //Make sure a file was posted
            string contentType = "application/octet-stream";

            Stream stream = new MemoryStream(byteArray);

             _blobKey = string.Format(_blobKey,azureAccountName, azureAccountKey);//Blob Key
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_blobKey);

            // Create the blob client
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container
            CloudBlobContainer container = blobClient.GetContainerReference(savePath);

            // Retrieve reference to a blob named "myblob"
            CloudBlockBlob blob = container.GetBlockBlobReference(fileName);

            // Create or overwrite the "myblob" blob with contents from a local file
            blob.Properties.ContentType = contentType;
            blob.UploadFromStream(stream);

            return fileName;
        }

        public void DelBlob(string fileName)
        {

            //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_blobKey);

             Create the blob client
            //CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

             Retrieve a reference to a container
            //CloudBlobContainer container = blobClient.GetContainerReference("upload");

             Retrieve reference to a blob named "myblob"
            //CloudBlockBlob blob = container.GetBlockBlobReference(fileName);

            //if (blob.Exists())
            //    blob.DeleteAsync();
        }

        private bool Exists(CloudBlob blob)
        {
            try
            {
                blob.FetchAttributes();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        public byte[] ReadToEnd(System.IO.Stream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position = 0;
            }

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }
                return buffer;
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }

        #endregion 上传到微软云
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值