/// <summary> /// SyncTest /// </summary> /// <returns></returns> private static void SyncTest() { StorageNode storageNode = FastDFSClient.GetStorageNode("group1"); 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); var binaryReader = new BinaryReader(fileStream); byte[] numArray; try { numArray = binaryReader.ReadBytes((int)fileStream.Length); } finally { binaryReader.Dispose(); } var str = FastDFSClient.UploadFile(storageNode, numArray, "jpg"); Console.WriteLine(StorageLink + str); FastDFSClient.RemoveFile("group1", str); Console.WriteLine("FastDFSClient.RemoveFile" + str); } }
/// <summary> /// 初始化节点 /// </summary> protected void InitStorageNode() { //读取配置文件中的fdfs配置节 var config = FastDfsManager.GetConfigSection(); try { //注意需要先初始化tracker ConnectionManager.InitializeForConfigSection(config); this.DFSGroupName = config.GroupName; this.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); } }
static ClientProxy() { var config = Configuration.ConfigHelper.CurrentConfig; List <IPEndPoint> trackerIPs = new List <IPEndPoint>(); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(config.TrackerList.First().IP), config.TrackerList.First().Port); trackerIPs.Add(endPoint); ConnectionManager.Initialize(trackerIPs); _node = FastDFSClient.GetStorageNode("group1"); }
/// <summary> /// 链接 FASTDFS /// </summary> static FastDFSHelper() { string[] trackers = ConfigHelper.GetValue("FastDFS", "fastdfs_trackers")?.Split(new char[','], StringSplitOptions.RemoveEmptyEntries); string[] storages = ConfigHelper.GetValue("FastDFS", "fastdfs_storages")?.Split(new char[','], StringSplitOptions.RemoveEmptyEntries); int port = int.Parse(ConfigHelper.GetValue("FastDFS", "fastdfs_port")); foreach (var onetracker in trackers) { trackerIPs.Add(new IPEndPoint(IPAddress.Parse(onetracker), port)); } ConnectionManager.Initialize(trackerIPs); storageNode = FastDFSClient.GetStorageNode(groupName); }
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); }
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); }
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(); }
/// <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"); }
/// <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"); } }
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); }
/// <summary> /// 废弃 /// </summary> static void Init() { try { var trackerIPs = new List <IPEndPoint>(); var strIPs = ConfigurationManager.AppSettings["TrackerIPS"]; if (!string.IsNullOrEmpty(strIPs)) { var strArray = strIPs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < strArray.Length; i++) { var strArray_i = strArray[i].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); trackerIPs.Add(new IPEndPoint(IPAddress.Parse(strArray_i[0]), Convert.ToInt32(strArray_i[1]))); } } ConnectionManager.Initialize(trackerIPs); Node = FastDFSClient.GetStorageNode("group1"); } catch (Exception ex) { Console.Write(ex.Message); } }
static void Main(string[] args) { //===========================Initial======================================== List <IPEndPoint> trackerIPs = new List <IPEndPoint>(); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("10.0.21.101"), 22122); trackerIPs.Add(endPoint); ConnectionManager.Initialize(trackerIPs); StorageNode node = FastDFSClient.GetStorageNode(); //===========================UploadFile===================================== byte[] content = null; string filename = @"D:\软件开发\OS\FastDFS\file\4.jpg"; if (File.Exists(filename)) { FileStream streamUpload = new FileStream(filename, FileMode.Open); using (BinaryReader reader = new BinaryReader(streamUpload)) { content = reader.ReadBytes((int)streamUpload.Length); } } //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb"); string fileName = FastDFSClient.UploadFile(node, content, "jpg"); FastDFSClient.DownloadFileEx(node, fileName, @"D:\软件开发\OS\FastDFS\file", "5.jpg"); Console.ReadKey(); //===========================BatchUploadFile===================================== string[] _FileEntries = Directory.GetFiles(@"E:\fastimage\三维", "*.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"); } DateTime end = DateTime.Now; TimeSpan consume = ((TimeSpan)(end - start)); double consumeSeconds = Math.Ceiling(consume.TotalSeconds); //===========================QueryFile======================================= fileName = "M00/00/00/wKhR6U__-BnxYu0eAxRgAJZBq9Q180.mdb"; FDFSFileInfo fileInfo = FastDFSClient.GetFileInfo(node, fileName); Console.WriteLine(string.Format("FileName:{0}", fileName)); Console.WriteLine(string.Format("FileSize:{0}", fileInfo.FileSize)); Console.WriteLine(string.Format("CreateTime:{0}", fileInfo.CreateTime)); Console.WriteLine(string.Format("Crc32:{0}", fileInfo.Crc32)); //==========================AppendFile======================================= FastDFSClient.AppendFile("group1", fileName, content); FastDFSClient.AppendFile("group1", fileName, content); //===========================DownloadFile==================================== fileName = "M00/00/00/wKhR6U__-BnxYu0eAxRgAJZBq9Q180.mdb"; 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(); //===========================RemoveFile======================================= FastDFSClient.RemoveFile("group1", fileName); //===========================Http测试,流读取======================================= string url = "http://img13.360buyimg.com/da/g5/M02/0D/16/rBEDik_nOJ0IAAAAAAA_cbJCY-UAACrRgMhVLEAAD-J352.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("c:\\fast.jpg");//保存 //===========================Http测试,直接下载======================================= WebClient web = new WebClient(); web.DownloadFile("http://img13.360buyimg.com/da/g5/M02/0D/16/rBEDik_nOJ0IAAAAAAA_cbJCY-UAACrRgMhVLEAAD-J352.jpg", "C:\\abc.jpg"); web.DownloadFile("http://192.168.81.233/M00/00/00/wKhR6VADbNr5s7ODAAIOGO1_YmA574.jpg", "C:\\abc.jpg"); Console.WriteLine("Complete"); Console.Read(); }
static void Main(string[] args) { #region 初始化 // 所有 tracker 服务器的ip:port var trackerIPs = new List <IPEndPoint>() { new IPEndPoint(IPAddress.Parse("192.168.181.128"), 22122) }; if (!ConnectionManager.Initialize(trackerIPs)) { throw new Exception("fastDFS连接初始化失败!"); } var node = FastDFSClient.GetStorageNode("group1"); #endregion #region 小文件上传 //var uploadingfilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\1.jpg"); //var uploadedfileUrl1 = MyFastDFSClient.UploadFile(node, uploadingfilePath); //Console.WriteLine($"小文件已上传,Url 为:{uploadedfileUrl1}"); //var slaveFileName = FastDFSClient.UploadSlaveFile("group1", content, fileName, "-part1", "jpg"); #endregion #region 大文件上传 #endregion #region 文件查询 var queryFileUrl = "M00/00/00/wKi1gF5LsuiAdeRbAAYD2YvCnl8857.jpg"; try { var fileInfo = FastDFSClient.GetFileInfo(node, queryFileUrl); Console.WriteLine($"文件大小:{fileInfo.FileSize}"); Console.WriteLine($"文件创建时间:{fileInfo.CreateTime.AddHours(8):yyyy-MM-dd HH:mm:ss}"); } catch (FDFSException ex) { Console.WriteLine($"文件不存在:{queryFileUrl}"); Console.WriteLine($"Message:{ex.Message}"); } #endregion #region 小文件下载 var downloadingfileUrl = "M00/00/00//wKi1gF5LsuiAdeRbAAYD2YvCnl8857.jpg"; var localPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"..\..\download\1{Path.GetExtension(downloadingfileUrl)}"); // 出现图片内容丢失 //var downloadingfileBytes = FastDFSClient.DownloadFile(node, downloadingfileUrl); //File.WriteAllBytes(localPath, downloadingfileBytes); //var downloadingfileUrl = $"http://192.168.181.128:8888/group1/{downloadingfileUrl}"; //using (WebClient web = new WebClient()) //{ // Directory.CreateDirectory(Path.GetDirectoryName(localPath)); // web.DownloadFile(downloadingfileUrl, localPath); // //Console.WriteLine("文件已下载完毕,稍后将自动打开。。。"); // //Process.Start("explore.exe", localPath); //} #endregion #region 大文件下载 #endregion #region 文件删除 var removingfileName = "M00/00/00/wKi1gF5LsuiAdeRbAAYD2YvCnl8857.jpg"; try { FastDFSClient.RemoveFile(node.GroupName, removingfileName); Console.WriteLine($"文件已删除:{removingfileName}"); } catch (FDFSException ex) { Console.WriteLine($"文件不存在:{queryFileUrl}"); Console.WriteLine($"Message:{ex.Message}"); } #endregion Console.WriteLine("ending........................"); Console.ReadKey(); }
private void InitStorageNode() { Node = FastDFSClient.GetStorageNode(DFSGroupName); Host = Node.EndPoint.Address.ToString(); }
static void Main(string[] args) { //===========================Initial======================================== List <IPEndPoint> trackerIPs = new List <IPEndPoint>(); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.81.233"), 22122); trackerIPs.Add(endPoint); ConnectionManager.Initialize(trackerIPs); StorageNode node = FastDFSClient.GetStorageNode("group1"); //===========================UploadFile===================================== byte[] content = null; if (File.Exists(@"D:\材料科学与工程基础.doc")) { FileStream streamUpload = new FileStream(@"D:\材料科学与工程基础.doc", FileMode.Open); using (BinaryReader reader = new BinaryReader(streamUpload)) { content = reader.ReadBytes((int)streamUpload.Length); } } //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb"); //主文件 string fileName = FastDFSClient.UploadFile(node, content, "doc"); //UploadFileByName //string fileName = FastDFSClient.UploadFileByName(node, @"D:\材料科学与工程基础.doc"); //从文件 string slavefileName = FastDFSClient.UploadSlaveFile("group1", content, fileName, "-part1", "doc"); //===========================BatchUploadFile===================================== string[] _FileEntries = Directory.GetFiles(@"E:\fastimage\三维", "*.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"); } DateTime end = DateTime.Now; TimeSpan consume = ((TimeSpan)(end - start)); double consumeSeconds = Math.Ceiling(consume.TotalSeconds); //===========================QueryFile======================================= fileName = "M00/03/80/wKhR6VAhwA72jCDyAABYAMjfFsM288.doc"; FDFSFileInfo fileInfo = FastDFSClient.GetFileInfo(node, fileName); Console.WriteLine(string.Format("FileName:{0}", fileName)); Console.WriteLine(string.Format("FileSize:{0}", fileInfo.FileSize)); Console.WriteLine(string.Format("CreateTime:{0}", fileInfo.CreateTime)); Console.WriteLine(string.Format("Crc32:{0}", fileInfo.Crc32)); //==========================AppendFile======================================= FastDFSClient.AppendFile("group1", fileName, content); FastDFSClient.AppendFile("group1", fileName, content); //===========================DownloadFile==================================== fileName = "M00/00/00/wKhR6VAAAN7J2FLQAABYAMjfFsM849.doc"; string localName = @"D:\SZdownload.doc"; if (File.Exists(@"D:\SZdownload.doc")) { File.Delete(@"D:\SZdownload.doc"); } 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(); //===========================RemoveFile======================================= //FastDFSClient.RemoveFile("group1", fileName); //===========================Http测试,流读取======================================= string url = "http://img13.360buyimg.com/da/g5/M02/0D/16/rBEDik_nOJ0IAAAAAAA_cbJCY-UAACrRgMhVLEAAD-J352.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("c:\\fast.jpg");//保存 //===========================Http测试,直接下载======================================= using (WebClient web = new WebClient()) { web.DownloadFile("http://img13.360buyimg.com/da/g5/M02/0D/16/rBEDik_nOJ0IAAAAAAA_cbJCY-UAACrRgMhVLEAAD-J352.jpg", "C:\\abc.jpg"); web.DownloadFile("http://192.168.81.233/M00/00/00/wKhR6VADbNr5s7ODAAIOGO1_YmA574.jpg", "C:\\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://192.168.81.233/M00/03/81/wKhR6VAh0sfyH0AxAABYAMjfFsM301-part1.doc?token=" + pwd + "&ts=" + ts; string url1 = "http://192.168.81.233/M00/01/E0/wKhR6VANJBiInHb5AAClVeZnxGg341.pdf"; using (WebClient web = new WebClient()) { web.DownloadFile(anti_steel_url, "C:\\salve.doc"); } Console.WriteLine("Complete"); Console.Read(); }
public FastDFSService() { storageNode = FastDFSClient.GetStorageNode(config.GroupName); }
/// <summary> /// 上传文件 /// </summary> /// <param name="contentByte">文件数组</param> /// <param name="fileExt">文件拓展名</param> /// <returns></returns> public static FastDfsFile Upload(byte[] contentByte, string fileExt) { var node = FastDFSClient.GetStorageNode(Config.GroupName); return(new FastDfsFile(Config.GroupName, FastDFSClient.UploadFile(node, contentByte, fileExt.Trim('.')))); }