FastDFS NET示例

Program.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using FastDFS.Client;
using System.Drawing;

namespace FastDFS
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //===========================初始化========================================
            var trackerIPs = new List<IPEndPoint>();
            var endPoint = new IPEndPoint(IPAddress.Parse("193.112.***.225"), 22122);
            trackerIPs.Add(endPoint);
            ConnectionManager.Initialize(trackerIPs);
            var node = FastDFSClient.GetStorageNode("group1");
            //===========================上传文件=====================================
            byte[] content = null;
            if (File.Exists(@"E:\JSON.pdf"))
            {
                FileStream streamUpload = new FileStream(@"E:\JSON.pdf", FileMode.Open);
                using (BinaryReader reader = new BinaryReader(streamUpload))
                {
                    content = reader.ReadBytes((int)streamUpload.Length);
                }
            }
            //主文件
            string fileName = FastDFSClient.UploadFile(node, content, "pdf");
            Console.WriteLine(fileName);
           
            //从文件
            string slavefileName = FastDFSClient.UploadSlaveFile("group1", content, fileName, "-part1", "pdf");

            //===========================批量上传文件=====================================
            string[] _FileEntries = Directory.GetFiles(@"E:\图片\png", "*.jpg");
            DateTime start = DateTime.Now;
            foreach (string file in _FileEntries)
            {
                string name = Path.GetFileName(file);
                content = null;
                FileStream streamUpload = new FileStream(file, FileMode.Open);
                using (BinaryReader reader = new BinaryReader(streamUpload))
                {
                    content = reader.ReadBytes((int)streamUpload.Length);
                }
                //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
                fileName = FastDFSClient.UploadFile(node, content, "jpg");
                Console.WriteLine(fileName);
            }
            DateTime end = DateTime.Now;
            TimeSpan consume = ((TimeSpan)(end - start));
            double consumeSeconds = Math.Ceiling(consume.TotalSeconds);
            //===========================查询文件=======================================
            fileName = "M00/00/00/rBEADlzXgpyAE0dEAAoTzDMI0PY510.pdf";

            //http://193.112.***.225/group1/M00/00/00/rBAAC1rA21SAULJwAAoTzEG_OEk868.pdf
            //rBAAC1rA21SAULJwAAoTzEG_OEk868 - part1.pdf
            //rBAAC1rA26iAWFB7AACXK3PhcOQ326.jpg
            //rBAAC1rA27CAHqf4AAAUBnpdd - Q710.jpg
            //rBAAC1rA28WAUmITAABKJd12G1A489.jpg

            var fileInfo = FastDFSClient.GetFileInfo(node, fileName);
            Console.WriteLine("FileName:{0}", fileName);
            Console.WriteLine("FileSize:{0}", fileInfo.FileSize);
            Console.WriteLine("CreateTime:{0}", fileInfo.CreateTime);
            Console.WriteLine("Crc32:{0}", fileInfo.Crc32);
             //==========================追加文件=======================================
            //FastDFSClient.AppendFile("group1", fileName, content);
            //FastDFSClient.AppendFile("group1", fileName, content);

            //===========================下载文件====================================

            //===========================RemoveFile=======================================
            FastDFSClient.RemoveFile("group1", fileName);

            //===========================Http测试,流读取=======================================
            string url = "http://129.211.***.213:8888/group1/M00/00/00/rBEADlzXgsKABpjMAACXKxIRQg8665.jpg";
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
            Image myImage = Image.FromStream(res.GetResponseStream());
            myImage.Save("E:\\fast.jpg");//保存 
            //===========================Http测试,直接下载=======================================
            using (WebClient web = new WebClient())
            {
                web.DownloadFile("http://129.211.50.***:8888/group1/M00/00/00/rBEADlzXhF6AOuCeAAoTzDMI0PY385.pdf", "E:\\abc.pdf");
                web.DownloadFile("http://129.211.50.***:8888/group1/M00/00/00/rBEADlzXgsKABpjMAACXKxIRQg8665.jpg", "E:\\abc.jpg");
            }
            //===========================防盗链请求=======================================
            start = new DateTime(1970, 1, 1);
            end = DateTime.Now;
            consume = (TimeSpan)(end - start);
            int ts = (int)(consume.TotalSeconds);
            string pwd = FastDFS.Client.Util.GetToken("M00/03/81/wKhR6VAh0sfyH0AxAABYAMjfFsM301-part1.doc", ts, "FastDFS1qaz2wsxsipsd");
            string anti_steel_url = "http://129.211.***.213:8888/group1/M00/00/00/rBEADlzXhG-Ad8IQAACXKxIRQg8657.jpg?token=" + pwd + "&ts=" + ts;
            using (WebClient web = new WebClient())
            {
                web.DownloadFile(anti_steel_url, "C:\\salve.jpg");
            }

            Console.WriteLine("完成");
            Console.Read();
        }
    }
}

结果如图:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

通过 FastDFS API下载文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Drawing;
using FastDFS.Client;

namespace FastDFS
{
    internal class Program
    {
         private static void Main(string[] args)
        {
            //===========================初始化========================================
            var trackerIPs = new List<IPEndPoint>();
            var endPoint = new IPEndPoint(IPAddress.Parse("129.211.***.213"), 22122);
            trackerIPs.Add(endPoint);
            ConnectionManager.Initialize(trackerIPs);
            var node = FastDFSClient.GetStorageNode("group1");
           
            //===========================下载文件====================================
            string fileName = "M00/00/00/rBEADlzXhF6AOuCeAAoTzDMI0PY385.pdf";
            FDFSFileInfo fileInfo = FastDFSClient.GetFileInfo(node, fileName);
            string localName = @"D:\mydownload.pdf";
            if (File.Exists(@"D:\mydownload.pdf"))
            {
                File.Delete(@"D:\mydownload.pdf");
            }

            if (fileInfo.FileSize >= 1024)//如果文件大小大于1KB  分次写入
            {
                FileStream fs = new FileStream(localName, FileMode.OpenOrCreate, FileAccess.Write);
                //string name_ = LocalName.Substring(LocalName.LastIndexOf("\\") + 1, LocalName.Length - LocalName.LastIndexOf("\\") - 1);
                long offset = 0;
                long len = 1024;
                while (len > 0)
                {
                    byte[] buffer = new byte[len];
                    buffer = FastDFSClient.DownloadFile(node, fileName, offset, len);
                    fs.Write(buffer, 0, int.Parse(len.ToString()));
                    fs.Flush();
                    // setrichtext(name_ + "已经下载:" + (offset / fileInfo.FileSize) + "%");
                    offset = offset + len;
                    len = (fileInfo.FileSize - offset) >= 1024 ? 1024 : (fileInfo.FileSize - offset);
                }
                fs.Close();

            }
            else//如果文件大小小小于1KB  直接写入文件
            {
                byte[] buffer = new byte[fileInfo.FileSize];
                buffer = FastDFSClient.DownloadFile(node, fileName);
                FileStream fs = new FileStream(localName, FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(buffer, 0, buffer.Length);
                fs.Flush();
                fs.Close();
            }


            //byte[] buffer = FastDFSClient.DownloadFile(node, fileName, 0L, 0L);
            //if (File.Exists(@"D:\SZdownload.mdb"))
            //    File.Delete(@"D:\SZdownload.mdb");
            //FileStream stream = new FileStream(@"D:\SZdownload.mdb", FileMode.CreateNew);
            //using (BinaryWriter write = new BinaryWriter(stream, Encoding.BigEndianUnicode))
            //{
            //    write.Write(buffer);
            //    write.Close();
            //}
            //stream.Close();

            Console.WriteLine("完成");
            Console.Read();
        }
    }
}

结果如图:

在这里插入图片描述
在这里插入图片描述

使用单例初始化

FastDFSHelper.cs

  /// <summary>
    /// FastDFSHelper 的摘要说明
    /// </summary>
    public static class FastDFSHelper
    {
        /// <summary>
        /// 是否已经初始化
        /// </summary>
        private static bool _isInitialize;

        /// <summary>
        /// 静态锁
        /// </summary>
        private static readonly object InitializeLock = new object();

        /// <summary>
        /// 初始Connection
        /// </summary>
        public static void FastDfsInitialize()
        {
            if (!_isInitialize)
            {
                lock (InitializeLock)
                {
                    if (!_isInitialize)
                    {
                        List<IPEndPoint> trackerIPs = new List<IPEndPoint>();
                        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("129.211.50.213"), 22122);
                        trackerIPs.Add(endPoint);
                        ConnectionManager.Initialize(trackerIPs);
                        _isInitialize = true;
                    }
                }
            }
        }
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值