Exemplo n.º 1
0
        /// <summary>
        /// UploadAsync2
        /// </summary>
        /// <param name="storageLink"></param>
        /// <param name="fileBytes"></param>
        /// <returns></returns>
        private static async Task UploadAsync2(string storageLink, Stream stream)
        {
            StorageNode storageNode = await FastDFSClient.GetStorageNodeAsync("group1");

            var str = await FastDFSClient.UploadFileAsync(storageNode, stream, "jpg", CancellationToken.None);

            Console.WriteLine(storageLink + str);
            stream.Dispose();

            await FastDFSClient.RemoveFileAsync("group1", str, CancellationToken.None);

            Console.WriteLine("FastDFSClient.RemoveFile" + str);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 链接 FASTDFS
        /// </summary>
        public FastDFSHelper()
        {
            string[] trackers = ConfigurationManager.AppSettings["fastdfs_trackers"].Split(new char[','], StringSplitOptions.RemoveEmptyEntries);
            string[] storages = ConfigurationManager.AppSettings["fastdfs_storages"].Split(new char[','], StringSplitOptions.RemoveEmptyEntries);
            int      port     = int.Parse(ConfigurationManager.AppSettings["fastdfs_port"]);

            foreach (var onetracker in trackers)
            {
                trackerIPs.Add(new IPEndPoint(IPAddress.Parse(onetracker), port));
            }
            ConnectionManager.Initialize(trackerIPs);
            storageNode = FastDFSClient.GetStorageNode(groupName);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            var config = FastDfsManager.GetConfigSection();

            StorageNode storageNode = null;

            var fileName = "";

            ConnectionManager.InitializeForConfigSection(config);

            do
            {
                // Console.WriteLine("\r\n1.Init");
                Console.WriteLine("\r\n");
                Console.WriteLine("1.GetAllStorageNode");
                Console.WriteLine("2.GetStorageNode");
                Console.WriteLine("3.UploadFile");
                Console.WriteLine("4.RemoveFile");

                Console.Write("请输入命令:");
                var cmd = Console.ReadLine();

                switch (cmd)
                {
                case "1":
                    var list = FastDFSClient.GetStorageNodes(config.GroupName);
                    foreach (var item in list)
                    {
                        Console.WriteLine(item.EndPoint.ToString());
                        Console.WriteLine(item.StorePathIndex);
                    }
                    break;

                case "2":
                    storageNode = FastDFSClient.GetStorageNode(config.GroupName);
                    Console.WriteLine(storageNode.GroupName);
                    Console.WriteLine(storageNode.EndPoint);
                    Console.WriteLine(storageNode.StorePathIndex);
                    break;

                case "3":
                    fileName = FastDFSClient.UploadFile(storageNode, File.ReadAllBytes("test.jpg"), "jpg");
                    Console.WriteLine(fileName);
                    break;

                case "4":
                    FastDFSClient.RemoveFile(config.GroupName, fileName);
                    break;
                }
            } while (true);
        }
Exemplo n.º 4
0
        public string Post()
        {
            var            request = HttpContext.Current.Request;
            HttpPostedFile file    = request.Files[0];

            string filename = "";

            if (ConfigHelper.GetConfigString("SaveMode") == "Local")  // 表示存储的是本地模式
            {
                var hostname = request.QueryString["host"] ?? "";

                if (hostname.StartsWith("www."))
                {
                    hostname = hostname.Remove(0, 4);
                }
                string savePath = string.Join("\\", hostname.Split('.').Reverse());
                savePath += "\\Upload\\" + GetPathRule();
                string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, savePath);
                if (!Directory.Exists(localPath))
                {
                    Directory.CreateDirectory(localPath);
                }

                string ex = Path.GetExtension(file.FileName);

                if (ConfigHelper.GetConfigString("SaveFileRule") == "Guid")
                {
                    filename = Guid.NewGuid().ToString("N") + ex;
                }
                else
                {
                    filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ex;
                }

                file.SaveAs(Path.Combine(localPath, filename));
                filename = request.Url.Scheme + "://" + request.Url.Authority + "/" + savePath.Replace("\\", "/") + "/" + filename;
            }
            else if (ConfigHelper.GetConfigString("SaveMode") == "Distributed")  //分布式模式
            {
                byte[] fileData;
                using (var binaryReader = new BinaryReader(file.InputStream))
                {
                    fileData = binaryReader.ReadBytes(file.ContentLength);
                }

                var storageNode = FastDFSClient.GetStorageNode(FastDfsGlobalConfig.Config.GroupName);
                var fileName    = FastDFSClient.UploadFile(storageNode, fileData, Path.GetExtension(file.FileName).TrimStart('.'));
                return(ConfigHelper.GetConfigString("TrackerHost") + FastDfsGlobalConfig.Config.GroupName + "/" + fileName);
            }
            return(filename);
        }
Exemplo n.º 5
0
        /// <summary>
        /// TestGetFileInfo
        /// </summary>
        private static void TestGetFileInfo()
        {
            StorageNode storageNode = FastDFSClient.GetStorageNode("group1");

            var          str      = "M00/00/81/CgE-EFm42mCARBiqAADl7mZ3mRU647.png";
            FDFSFileInfo fileInfo = FastDFSClient.GetFileInfo(storageNode, str);

            Console.WriteLine("FileName:{0}", str);
            Console.WriteLine("FileSize:{0}", fileInfo.FileSize);
            Console.WriteLine("CreateTime:{0}", fileInfo.CreateTime);
            Console.WriteLine("Crc32:{0}", fileInfo.Crc32);

            Console.WriteLine("Complete");
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            var stream = new FileStream(@"D:\1.jpg", FileMode.Open);

            ConnectionManager.Initialize(new List <IPEndPoint> {
                new IPEndPoint(IPAddress.Parse("172.16.2.154"), 22122)
            });
            var g     = FastDFSClient.GetStorageNode("group2");
            var bytes = new byte[stream.Length];

            stream.Read(bytes, 0, bytes.Length);
            //FastDFSClient.UploadFile(g, b, "jpg");
            Console.ReadKey();
        }
Exemplo n.º 7
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name=""></param>
        /// <returns>文件流</returns>
        public byte[] DownloadFileByte(string fileName)
        {
            FDFSFileInfo fileInfo = FastDFSClient.GetFileInfo(storageNode, fileName);

            byte[] buffer = new byte[fileInfo.FileSize];
            buffer = FastDFSClient.DownloadFile(storageNode, fileName);

            FileStream fs = new FileStream("D://down123.png", FileMode.Create, FileAccess.Write);

            fs.Write(buffer, 0, buffer.Length);
            fs.Flush();
            fs.Close();

            return(buffer);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 上传图片到图片服务器
        /// </summary>
        /// <param name="FileUpload1">控件名称</param>
        /// <param name="filepath">
        /// 虚拟文件路径
        /// 例如:UploadImages/PicProduct
        /// </param>
        /// <returns></returns>
        public string UpLoadToServer(byte[] imageData, string extName, string configPath)
        {
            try
            {
                FastDFSClient DFSClient   = new FastDFSClient(configPath);
                StorageNode   storage     = DFSClient.GetStorageNode("g1");
                string        dfsFilePath = DFSClient.UploadFile(storage, imageData, extName);

                return(dfsFilePath);
            }
            catch
            {
                return("error");
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 文件分块上传,适合大文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private string MultipartUpload(Stream stream, string ext)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream参数不能为空");
            }
            int size = 1024 * 1024;

            byte[] content = new byte[size];
            //  第一个数据包上传或获取已上传的位置
            stream.Read(content, 0, size);
            string shortName = FastDFSClient.UploadAppenderFile(Node, content, ext);

            BeginUploadPart(stream, shortName, size);
            return(CompleteUpload(stream, shortName));
        }
Exemplo n.º 10
0
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="param"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public ImageUploadResult UploadImage(ImageUploadParameter param)
        {
            byte[] content;
            string shortName = "";
            //1 获取拓展名
            string ext = System.IO.Path.GetExtension(param.FileName).ToLower();

            //1.2判断上传图片对象中的拓展名是否与实际拓展名相符
            //若上传图片对象的拓展名为空或不行相符
            if (param.FilenameExtension != null && param.FilenameExtension.Contains(ext))
            {
                if (param.Stream.Length > param.MaxSize)
                {
                    return(new ImageUploadResult
                    {
                        ErrorMessage = "图片大小超过指定大小" + param.MaxSize / (1024 * 1024) + "M,请重新选择",
                        FullFilePath = shortName
                    });
                }
                else
                {
                    using (BinaryReader reader = new BinaryReader(param.Stream))
                    {
                        content = reader.ReadBytes((int)param.Stream.Length);
                    }

                    //**注意 调用FdfsClient的UploadFile时,拓展名不含.,需要手动去掉
                    //**注意返回值为:M00/00/00/wKgAcVjGSpSANp6XAAInn_BrY3k752.jpg
                    shortName = FastDFSClient.UploadFile(Node, content, ext.Contains('.') ? ext.Substring(1) : ext);
                }
            }
            else
            {
                return(new ImageUploadResult
                {
                    ErrorMessage = "文件类型不匹配",
                    FullFilePath = shortName
                });
            }
            return(new ImageUploadResult
            {
                FullFilePath = CompleteUpload(param.Stream, shortName),
                FileName = shortName,
                GroupName = Node.GroupName,
                Url = Host
            });
        }
Exemplo n.º 11
0
        public override int Run(string[] remainingArguments)
        {
            string filename = remainingArguments.FirstOrDefault();

            if (_dryrun)
            {
                Console.WriteLine("fdfsclient upload {0} {1}", OptionsToString(), filename);
                return(0);
            }
            ConnectionManager.Initialize(_trackers);
            StorageNode node   = FastDFSClient.GetStorageNode("group1");
            string      fileid = DoUpload(node, filename);

            Console.WriteLine("{0}", fileid);
            Console.WriteLine("http://{0}/{1}", _trackers[0].Address.ToString(), fileid);
            return(0);
        }
Exemplo n.º 12
0
        public static async Task <string> UpdateFile(Stream fileStream, string fileExt = "jpg", string groupName = "group1")
        {
            if (fileStream == null)
            {
                throw new ArgumentNullException(nameof(fileStream));
            }

            byte[] content = new byte[fileStream.Length];

            using (BinaryReader reader = new BinaryReader(fileStream))
            {
                content = reader.ReadBytes((int)fileStream.Length);
            }

            var node = await FastDFSClient.GetStorageNodeAsync(groupName);

            return(await FastDFSClient.UploadFileAsync(node, content, fileExt));
        }
Exemplo n.º 13
0
        private static async Task <(string GroupName, string filename)> UploadAppenderFileAsync()
        {
            Console.WriteLine("UploadAppenderFile");
            StorageNode storageNode = await FastDFSClient.GetStorageNodeAsync();

            Console.WriteLine($"{nameof(storageNode.EndPoint)}: {storageNode.EndPoint}");
            Console.WriteLine($"{nameof(storageNode.GroupName)}: {storageNode.GroupName}");
            Console.WriteLine($"{nameof(storageNode.StorePathIndex)}: {storageNode.StorePathIndex}");

            byte[] data     = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
            string filename = await FastDFSClient.UploadAppenderFileAsync(storageNode, data, ".txt");

            Console.WriteLine($"{filename}\n");

            await GetFileInfoAsync(storageNode, filename);

            return(storageNode.GroupName, filename);
        }
Exemplo n.º 14
0
        public string UploadFile(string fileName, byte[] fileContent)
        {
            if (null == fileContent || fileContent.Count() <= 0)
            {
                Enforce.Throw(new Exception("文件内容不能为空"));
            }
            string fileExtension = Path.GetExtension(fileName);

            if (string.IsNullOrEmpty(fileExtension))
            {
                Enforce.ArgumentNotNull <string>(fileExtension, "文件后缀名不能为空");
            }
            fileExtension = fileExtension.TrimStart('.');

            string fileID = FastDFSClient.UploadFile(storageNode, fileContent, fileExtension);

            return(fileID);
        }
Exemplo n.º 15
0
        /// <summary>
        /// UploadAsync
        /// </summary>
        /// <param name="storageLink"></param>
        /// <returns></returns>
        private static async Task UploadAsync(string storageLink)
        {
            StorageNode storageNode = await FastDFSClient.GetStorageNodeAsync("group1", "server");

            string[] files     = Directory.GetFiles("testimage", "*.jpg");
            string[] strArrays = files;
            for (int i = 0; i < strArrays.Length; i++)
            {
                string str1     = strArrays[i];
                var    numArray = GetFileBytes(str1);
                var    str      = await FastDFSClient.UploadFileAsync(storageNode, numArray, "jpg", "default");

                Console.WriteLine(storageLink + str);
                await FastDFSClient.RemoveFileAsync("group1", str, "default");

                Console.WriteLine("FastDFSClient.RemoveFile" + str);
            }
        }
Exemplo n.º 16
0
        protected static async Task BigFileUploadDownLoad()
        {
            var         temp        = Enumerable.Repeat((byte)99, 1024 * 1024 * 100);
            var         testBytes   = temp.ToArray();
            StorageNode storageNode = await FastDFSClient.GetStorageNodeAsync("group1", "default");

            var filename = await FastDFSClient.UploadFileAsync(storageNode, testBytes, "txt", "default");

            using (var fileStream = File.OpenWrite("c:\\fastdfs_test.txt"))
            {
                await FastDFSClient.DownloadFileAsync(storageNode, filename, new StreamDownloadCallback(fileStream), "default");
            }

            await FastDFSClient.RemoveFileAsync("group1", filename, "default");

            temp      = null;
            testBytes = null;
        }
Exemplo n.º 17
0
        /// <summary>
        /// 从指定位置开始上传文件
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="beginOffset"></param>
        /// <param name="serverShortName"></param>
        private void BeginUploadPart(Stream stream, string serverShortName, int bufferSize)
        {
            try
            {
                byte[] content = new byte[bufferSize];

                while (stream.Position < stream.Length)
                {
                    stream.Read(content, 0, bufferSize);

                    var result = FastDFSClient.AppendFile(DFSGroupName, serverShortName, content);
                    Console.WriteLine("分块上传开始,大小:" + bufferSize);
                    if (result.Length == 0)
                    {
                        FaildCount = 0;
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Info("上传文件中断!" + ex.Message);
                if (NetCheck())
                {
                    //重试
                    if (FaildCount < MaxFaildCount)
                    {
                        FaildCount++;
                        InitStorageNode();
                        ContinueUploadPart(stream, serverShortName, bufferSize);
                    }
                    else
                    {
                        LoggerFactory.Instance.Logger_Info("已达到失败重试次数仍没有上传成功");;
                        throw ex;
                    }
                }
                else
                {
                    LoggerFactory.Instance.Logger_Info("当前网络不可用");
                    throw ex;
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// SyncTest
        /// </summary>
        /// <returns></returns>
        private static void SyncTest()
        {
            StorageNode storageNode = FastDFSClient.GetStorageNodeAsync("group1").GetAwaiter().GetResult();

            string[] files     = Directory.GetFiles("testimage", "*.jpg");
            string[] strArrays = files;
            for (int i = 0; i < strArrays.Length; i++)
            {
                string str1       = strArrays[i];
                var    fileStream = new FileStream(str1, FileMode.Open, FileAccess.Read);

                var str = FastDFSClient.UploadFileAsync(storageNode, fileStream, "jpg", CancellationToken.None
                                                        ).GetAwaiter().GetResult();
                fileStream.Dispose();
                Console.WriteLine(StorageLink + str);
                FastDFSClient.RemoveFileAsync("group1", str, CancellationToken.None).GetAwaiter().GetResult();;
                Console.WriteLine("FastDFSClient.RemoveFile" + str);
            }
        }
Exemplo n.º 19
0
        public static async Task <bool> RemoveAsync(string path)
        {
            var arr = path.Split("/");

            var groupName = arr[0];

            path = path.Remove(arr[0].Length);

            try
            {
                await FastDFSClient.RemoveFileAsync(groupName, path);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileStream">文件流</param>
        /// <param name="prefixName">从文件前缀名称</param>
        /// <param name="fileExt">文件后缀名</param>
        /// <param name="slaveFileName">返回从文件路径</param>
        /// <returns>返回主文件路径</returns>
        public string UploadFile(Stream fileStream, string prefixName, string fileExt, out string slaveFileName)
        {
            byte[] content = new byte[fileStream.Length];

            using (BinaryReader reader = new BinaryReader(fileStream))
            {
                content = reader.ReadBytes((int)fileStream.Length);
            }

            //主文件
            string fileName = FastDFSClient.UploadFile(storageNode, content, fileExt);
            var    info     = FastDFSClient.GetFileInfo(storageNode, fileName);

            //从文件
            slaveFileName = FastDFSClient.UploadSlaveFile(groupName, content, fileName, prefixName, fileExt);
            var slaveInfo = FastDFSClient.GetFileInfo(storageNode, slaveFileName);

            return(fileName);
        }
Exemplo n.º 21
0
        /// <summary>
        /// TestGetFileInfo
        /// </summary>
        private static async Task TestGetFileInfo()
        {
            StorageNode storageNode = await FastDFSClient.GetStorageNodeAsync("group1");

            var str      = "http://locahost/group1/M00/00/00/oYYBAFvcGZ2AGBAbAAAUa4KwmUU269.png";
            var fileInfo = await FastDFSClient.GetFileInfoAsync(str);

            if (fileInfo == null)
            {
                Console.WriteLine("Not Exist");
                return;
            }
            Console.WriteLine("FileName:{0}", str);
            Console.WriteLine("FileSize:{0}", fileInfo.FileSize);
            Console.WriteLine("CreateTime:{0}", fileInfo.CreateTime);
            Console.WriteLine("Crc32:{0}", fileInfo.Crc32);

            Console.WriteLine("Complete");
        }
Exemplo n.º 22
0
        protected void Button1_Click1(object sender, EventArgs e)
        {
            try
            {
                string guid = Guid.NewGuid().ToString();
                if (null != _logger)
                {
                    _logger.InfoFormat("上传文件的大小为:{0}字节!", FileUpload1.PostedFile.ContentLength);
                }
                DateTime begin = DateTime.Now;

                IList <Byte[]> list = new List <byte[]>();
                list.Add(FileUpload1.FileBytes);
                list.Add(FileUpload2.FileBytes);
                list.Add(FileUpload3.FileBytes);
                list.Add(FileUpload4.FileBytes);
                list.Add(FileUpload5.FileBytes);

                string[] filename = { Tooklit.GetExtension(FileUpload1.FileName), Tooklit.GetExtension(FileUpload2.FileName),
                                      Tooklit.GetExtension(FileUpload3.FileName), Tooklit.GetExtension(FileUpload4.FileName), Tooklit.GetExtension(FileUpload5.FileName) };

                FastDFSClient.BatchUpload("test", list, filename);



                TimeSpan span = DateTime.Now - begin;
                //if (null != _logger)
                //    _logger.InfoFormat("上传文件Id为:{0}!路径为{1}!", guid, filePath);
                if (null != _logger)
                {
                    _logger.InfoFormat("上传文件的时间为:{0}秒!", span.TotalSeconds);
                }
                Response.Write("上传成功!");
            }
            catch (Exception exc)
            {
                Response.Write("上传失败!");
                if (null != _logger)
                {
                    _logger.ErrorFormat("测试文件上传速度时发生异常:{0}" + exc.Message);
                }
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// TestGetFileInfo
        /// </summary>
        private static async Task TestGetFileInfo()
        {
            StorageNode storageNode = await FastDFSClient.GetStorageNodeAsync("group1");

            var          str      = "M00/0E/82/CgE-EFsTqKmAEHO7AADMG7XS9Fc7491.jpg";
            FDFSFileInfo fileInfo = await FastDFSClient.GetFileInfoAsync(storageNode, str);

            if (fileInfo == null)
            {
                Console.WriteLine("Not Exist");
                return;
            }
            Console.WriteLine("FileName:{0}", str);
            Console.WriteLine("FileSize:{0}", fileInfo.FileSize);
            Console.WriteLine("CreateTime:{0}", fileInfo.CreateTime);
            Console.WriteLine("Crc32:{0}", fileInfo.Crc32);

            Console.WriteLine("Complete");
        }
Exemplo n.º 24
0
        /// <summary>
        /// UploadAsync
        /// </summary>
        /// <param name="storageLink"></param>
        /// <returns></returns>
        private static async Task UploadAsync(string storageLink)
        {
            StorageNode storageNode = await FastDFSClient.GetStorageNodeAsync(group);

            string[] files     = Directory.GetFiles(@"C:\Users\Administrator.DESKTOP-LOM86CH\Desktop\images");
            string[] strArrays = files;
            for (int i = 0; i < strArrays.Length; i++)
            {
                string str1     = strArrays[i];
                var    numArray = GetFileBytes(str1);

                //务必保存此文件路径
                var str = await FastDFSClient.UploadFileAsync(storageNode, numArray, "jpg");

                Console.WriteLine(storageLink + str);
                await FastDFSClient.RemoveFileAsync(group, str);

                Console.WriteLine("FastDFSClient.RemoveFile" + str);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// 文件分块上传,适合大文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private string MultipartUpload(UploadParameterBase param)
        {
            Stream stream = param.Stream;

            if (stream == null)
            {
                throw new ArgumentNullException("stream参数不能为空");
            }
            byte[] content      = new byte[SIZE];
            Stream streamUpload = stream;
            //  第一个数据包上传或获取已上传的位置
            string ext = param.FileName.Substring(param.FileName.LastIndexOf('.') + 1);

            streamUpload.Read(content, 0, SIZE);
            string shortName = FastDFSClient.UploadAppenderFile(Node, content, ext);

            BeginUploadPart(stream, shortName);

            return(CompleteUpload(stream, shortName));
        }
Exemplo n.º 26
0
        public async Task ListOneGroupInfoAsync_Test()
        {
            var mockExecuter       = new Mock <IExecuter>();
            var mockClusterFactory = new Mock <IClusterFactory>();

            mockExecuter.Setup(x => x.Execute(It.IsAny <FastDFSReq <ListOneGroupResp> >(), It.IsAny <string>(), It.IsAny <ConnectionAddress>())).ReturnsAsync(new ListOneGroupResp()
            {
                GroupInfo = new GroupInfo()
                {
                    GroupName = "group2"
                }
            });

            IFastDFSClient client    = new FastDFSClient(mockExecuter.Object, mockClusterFactory.Object);
            var            groupInfo = await client.ListOneGroupInfoAsync("group1");

            Assert.Equal("group2", groupInfo.GroupName);

            mockExecuter.Verify(x => x.Execute(It.IsAny <FastDFSReq <ListOneGroupResp> >(), It.IsAny <string>(), It.IsAny <ConnectionAddress>()), Times.Once);
        }
Exemplo n.º 27
0
        public async Task GetStorageNodeAsync_Test()
        {
            var mockExecuter       = new Mock <IExecuter>();
            var mockClusterFactory = new Mock <IClusterFactory>();

            mockExecuter.Setup(x => x.Execute(It.IsAny <FastDFSReq <QueryStoreWithGroupResp> >(), It.IsAny <string>(), It.IsAny <ConnectionAddress>())).ReturnsAsync(new QueryStoreWithGroupResp()
            {
                GroupName      = "group2",
                IPAddress      = "192.168.0.2",
                Port           = 23000,
                StorePathIndex = 0
            });
            IFastDFSClient client = new FastDFSClient(mockExecuter.Object, mockClusterFactory.Object);
            var            node   = await client.GetStorageNodeAsync("group1");

            Assert.Equal("group2", node.GroupName);
            Assert.Equal(new ConnectionAddress("192.168.0.2", 23000), node.ConnectionAddress);

            mockExecuter.Verify(x => x.Execute(It.IsAny <FastDFSReq <QueryStoreWithGroupResp> >(), It.IsAny <string>(), It.IsAny <ConnectionAddress>()), Times.Once);
        }
        /// <summary>
        /// 上传图片(商品)
        /// </summary>
        /// <returns></returns>
        public string GetUpLoad()
        {
            HttpPostedFileBase postFile = Request.Files["upLoad"];

            System.IO.Stream       s   = postFile.InputStream;
            byte[]                 bt  = new byte[postFile.ContentLength];
            System.IO.MemoryStream mes = new System.IO.MemoryStream(bt);
            s.Read(bt, 0, bt.Length);
            s.Close();
            int    w1         = string.IsNullOrEmpty(Request["w"]) ? 0 : int.Parse(Request["w"]);
            int    h1         = string.IsNullOrEmpty(Request["h"]) ? 0 : int.Parse(Request["h"]);
            string t          = postFile.ContentType;
            string imageTypes = "image/pjpeg,image/jpeg,image/gif,image/png,image/x-png";

            if (imageTypes.IndexOf(t) < 0)
            {
                return("1");
            }
            else
            {
                s.Read(bt, 0, bt.Length);
                s.Close();
                System.Drawing.Image image = System.Drawing.Image.FromStream(mes);

                //int H = image.Height;
                //int W = image.Width;
                //if (H < h1 || W < w1)
                //{
                //    return "2";
                //}
                //else
                //{
                //    string fileName = FastDFSClient.UploadFile(FastDFSClient.DefaultGroup, bt, "jpg");
                //   // fileName = new UploadFile().GetThumbsImage(fileName, 660, 200);
                //    return fileName;
                //}

                string fileName = FastDFSClient.UploadFile(FastDFSClient.DefaultGroup, bt, "jpg");
                return(fileName);
            }
        }
Exemplo n.º 29
0
        private static async Task DownLoadFile()
        {
            var         testBytes   = Encoding.UTF8.GetBytes("12345678911118888888888888888881111111111");
            StorageNode storageNode = await FastDFSClient.GetStorageNodeAsync("group1", "default");

            var filename = await FastDFSClient.UploadFileAsync(storageNode, testBytes, "txt", "default");

            var bytes = await FastDFSClient.DownloadFileAsync(storageNode, filename, "default");

            if (bytes == null)
            {
                Console.WriteLine($"DownLoadFile Fail : Bytes null ");
            }
            if (Encoding.UTF8.GetString(bytes) == Encoding.UTF8.GetString(testBytes))
            {
                Console.WriteLine($"DownLoadFile Success");
            }
            else
            {
                throw new ApplicationException("DownLoadFile Fail : Bytes Diff");
            }
        }
Exemplo n.º 30
0
        ///// <summary>
        ///// 初始化节点
        ///// </summary>
        //private void InitStorageNode()
        //{
        //    //读取配置文件中的fdfs配置节
        //    var config = FastDfsManager.GetConfigSection();
        //    try
        //    {
        //        //注意需要先初始化tracker
        //        ConnectionManager.InitializeForConfigSection(config);
        //        base.DFSGroupName = config.GroupName;
        //        base.Host = config.FastDfsServer.FirstOrDefault().IpAddress;
        //        //根据指定群组名称获取存储节点
        //        Node = FastDFSClient.GetStorageNode(config.GroupName);
        //        foreach (var item in config.FastDfsServer)
        //        {
        //            trackerIPs.Add(new IPEndPoint(IPAddress.Parse(item.IpAddress), item.Port));
        //        }
        //        //初始化
        //        ConnectionManager.Initialize(trackerIPs);
        //    }
        //    catch (Exception ex)
        //    {
        //        //Logger.LoggerFactory.Instance.Logger_Error(ex);
        //    }

        //    //Node = FastDFSClient.GetStorageNode(DFSGroupName);
        //    //Host = Node.EndPoint.Address.ToString();
        //}
        #endregion

        #region   时需要用到的方法


        /// <summary>
        /// 上传小文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private string SmallFileUpload(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filePath 参数不能为空");
            }
            if (!File.Exists(filePath))
            {
                throw new Exception("上传的文件不存在");
            }
            byte[] content;
            using (FileStream streamUpload = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader reader = new BinaryReader(streamUpload))
                {
                    content = reader.ReadBytes((int)streamUpload.Length);
                }
            }
            string shortName = FastDFSClient.UploadFile(Node, content, "png");

            return(GetFormatUrl(shortName));
        }