/// <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;
                string fileName = FastDFSClient.UploadFile(FastDFSClient.DefaultGroup, bt, "jpg");
                //fileName = new UploadFile().GetThumbsImage(fileName, 660, 600);
                return(fileName);
            }
        }
Exemple #2
0
 /// <summary>
 /// 上传文件公用类
 /// </summary>
 /// <param name="_file"></param>
 /// <returns></returns>
 public FileUploadResult UploadFileCommon(HttpPostedFileBase _file)
 {
     try
     {
         string _fileInfotype = _file.ContentType; //Path.GetExtension(file.FileName).ToLower();
         int    _fileInfosize = (int)_file.InputStream.Length;
         if (_fileInfosize == 0)
         {
             return(new FileUploadResult {
                 result = false, ResultExplain = "上传空文件"
             });
         }
         Stream stream = _file.InputStream;
         byte[] buffer = new byte[_fileInfosize];
         stream.Read(buffer, 0, _fileInfosize);
         var t = Path.GetExtension(_file.FileName);
         t = t == null ? "jpg" : t.Replace(".", "");
         //获得原图的路径
         string ImageUrl = FastDFSClient.UploadFile(FastDFSClient.DefaultGroup, buffer, t);
         //获得服务器地址
         string url = GetConfig.FullPath() + GetThumbsImage(ImageUrl, 364, 230);
         return(new FileUploadResult {
             url = url, ResultExplain = "成功", name = ImageUrl, result = true
         });
     }
     catch (Exception)
     {
         return(new FileUploadResult {
             url = "", ResultExplain = "失败", name = "", result = false
         });
     }
 }
Exemple #3
0
            /// <summary>
            /// 根据订单编号生成条形码(wuyf 2015-9-11)
            /// </summary>
            /// <param name="orderID">订单编号</param>
            /// <returns>返回条形码图片路径</returns>
            public static string GetTxm(string orderID)
            {
                //var imgpath = HKSJ.Common.ConfigHelper.GetConfigString("ImagePath") + orderID + ".jpg";
                var          imgpath = HKSJ.Common.ConfigHelper.GetConfigString("ImagePath");
                MemoryStream ms      = new MemoryStream();

                try
                {
                    Code.BarCode.Code128 _Code = new Code.BarCode.Code128();
                    _Code.ValueFont = new Font("宋体", 20);
                    //T26200-1900-123-1-0900
                    System.Drawing.Bitmap imgTemp = _Code.GetCodeImage(orderID, Code.BarCode.Code128.Encode.Code128A);
                    //imgTemp.Save(imgpath, System.Drawing.Imaging.ImageFormat.Gif);



                    imgTemp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                    byte[] bytes    = ms.GetBuffer(); //byte[]   bytes=   ms.ToArray(); 这两句都可以,至于区别么,下面有解释
                    var    fileName = FastDFSClient.UploadFile(FastDFSClient.DefaultGroup, bytes, "jpg");
                    imgpath += fileName;
                }
                catch (Exception ex)
                {
                    var opera = string.Format("生成条形码:{0},操作结果:{1}", ex.Message, "失败");
                    LogPackage.InserAC_OperateLog(opera, "PDF");
                }
                finally
                {
                    ms.Close();
                }


                return(imgpath);
            }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        static string GetFileNameByUpload(string filePath, string fileExt)
        {
            byte[] content        = null;
            var    returnFileName = string.Empty;

            try
            {
                if (File.Exists(filePath))
                {
                    using (FileStream fsRead = new FileStream(filePath, FileMode.Open))
                    {
                        using (BinaryReader reader = new BinaryReader(fsRead))
                        {
                            content = reader.ReadBytes((int)fsRead.Length);
                        }
                        returnFileName = FastDFSClient.UploadFile(Node, content, fileExt);
                    }
                }
            }
            catch (Exception)
            {
                returnFileName = "";
            }
            return(returnFileName);
        }
Exemple #5
0
        /// <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);
            }
        }
Exemple #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <param name="dir"></param>
        /// <param name="extendName"></param>
        /// <returns></returns>
        public string Upload(byte[] data, string dir, string extendName, int externalId)
        {
            string fileName = FastDFSClient.UploadFile(_node, data, extendName);
            var    server   = Configuration.ConfigHelper.CurrentConfig.HttpServer;

            if (!server.EndsWith("/"))
            {
                server = server + "/";
            }
            return(server + fileName);
        }
Exemple #7
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileStream">文件流</param>
        /// <param name="fileExt">文件后缀</param>
        /// <returns>返回主文件路径</returns>
        public static string UploadFile(Stream fileStream, string fileExt)
        {
            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);

            return(fileName);
        }
Exemple #8
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);
        }
Exemple #9
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);
        }
Exemple #10
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");
            }
        }
        /// <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
            });
        }
Exemple #12
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);
        }
Exemple #13
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);
        }
Exemple #14
0
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="param"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public ImageUploadResult UploadImage(ImageUploadParameter param)
        {
            byte[] content;
            string shortName = "";
            string ext       = System.IO.Path.GetExtension(param.FileName).ToLower();

            if (param.FilenameExtension != null && param.FilenameExtension.Contains(ext))
            {
                if (param.Stream.Length > param.MaxSize)
                {
                    return(new ImageUploadResult
                    {
                        ErrorMessage = "图片大小超过指定大小" + param.MaxSize / (1024 * 1024) + "M,请重新选择",
                        FilePath = shortName
                    });
                }
                else
                {
                    using (BinaryReader reader = new BinaryReader(param.Stream))
                    {
                        content = reader.ReadBytes((int)param.Stream.Length);
                    }

                    shortName = FastDFSClient.UploadFile(Node, content, ext.Contains('.') ? ext.Substring(1) : ext);
                }
            }
            else
            {
                return(new ImageUploadResult
                {
                    ErrorMessage = "文件类型不匹配",
                    FilePath = shortName
                });
            }
            return(new ImageUploadResult
            {
                FilePath = CompleteUpload(param.Stream, shortName),
            });
        }
        ///// <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));
        }
Exemple #16
0
 /// <summary>
 /// 上传文件
 /// </summary>
 /// <param name="fileStream">文件流</param>
 /// <param name="fileExt">文件后缀</param>
 /// <returns>返回主文件路径</returns>
 public static string UploadFile(string fileBase64, string fileName)
 {
     byte[] bytes = fileBase64.ToBytes_FromBase64Str();
     //主文件
     return(FastDFSClient.UploadFile(storageNode, bytes, Path.GetExtension(fileName).Replace(".", "")));
 }
Exemple #17
0
        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();
        }
        public ActionResult UploadImage()
        {
            var result = new ResultModel
            {
                IsValid = false
            };

            try
            {
                var postFile = this.Request.Files[0]; //上传文件对象

                if (postFile != null)
                {
                    var size = postFile.ContentLength.ToString();
                }
                if (postFile != null)
                {
                    var stream = postFile.InputStream;

                    var bt = new byte[postFile.ContentLength];
                    var ms = new MemoryStream(bt);

                    stream.Read(bt, 0, bt.Length);
                    stream.Close();

                    var    t       = postFile.ContentType;
                    string fileExt = System.IO.Path.GetExtension(postFile.FileName);
                    if (fileExt.Length > 0)
                    {
                        fileExt = fileExt.Substring(1, fileExt.Length - 1);
                    }

                    var imageTypes = "image/pjpeg,image/jpeg,image/gif,image/png,image/x-png/apk/ipa";

                    if (imageTypes.IndexOf(t, StringComparison.Ordinal) < 0)
                    {
                        result.Messages.Add("Please upload jpg, gif or png format picture");
                    }
                    else if (bt.Length > 1024 * 1024)  //wuyf 添加else
                    {
                        result.Messages.Add("Upload pictures of the size of the control in the range of 1M!");
                    }
                    else
                    {
                        var fileName = FastDFSClient.UploadFile(FastDFSClient.DefaultGroup, bt, fileExt);
                        result.IsValid = true;
                        result.Data    = fileName;
                    }
                }
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Messages.Add("upload failed");
                var opera = string.Empty;

                opera = "UploadController图片上传错误 ex:" + ex.Message;
                LogPackage.InserAC_OperateLog(opera, "UploadController图片上传");
                //todo 日志记录
            }
            return(this.Json(result, JsonRequestBehavior.AllowGet));
        }
        public ActionResult UploadFiles1()
        {
            var result = new ResultModel
            {
                IsValid = false
            };

            if (Request.Files != null)
            {
                //foreach (string file in Request.Files)
                //{
                HttpPostedFileBase hpf = Request.Files[0] as HttpPostedFileBase;
                if (hpf.ContentLength == 0)
                {
                }
                //判断文件是否合法
                string fileExt = System.IO.Path.GetExtension(hpf.FileName);
                int    apptype = Convert.ToInt32(Request["AppType"].Trim());
                if (apptype == 1)
                {
                    if (fileExt.ToUpper() != ".IPA")
                    {
                        result.Messages.Add("IOS platform, please upload the file suffix is.IPA");
                        result.IsValid = false;
                        return(this.Json(result, JsonRequestBehavior.AllowGet));
                    }
                }
                else
                {
                    if (fileExt.ToUpper() != ".APK")
                    {
                        result.Messages.Add("Android platform, please upload the file suffix is.APK");
                        result.IsValid = false;
                        return(this.Json(result, JsonRequestBehavior.AllowGet));
                    }
                }

                string                 size = hpf.ContentLength.ToString();
                System.IO.Stream       s    = hpf.InputStream;
                byte[]                 bt   = new byte[hpf.ContentLength];
                System.IO.MemoryStream mes  = new System.IO.MemoryStream(bt);
                s.Read(bt, 0, bt.Length);
                s.Close();

                try
                {
                    string fileName = FastDFSClient.UploadFile(FastDFSClient.DefaultGroup, bt, fileExt.Replace(".", ""));
                    result.IsValid = true;
                    result.Data    = fileName;
                    result.Messages.Add(size + "byte");
                }
                catch (Exception ex)
                {
                    result.IsValid = false;
                    result.Messages.Add("upload failed");
                    var opera = string.Empty;

                    opera = "UploadController文件上传错误 ex:" + ex.Message;
                    LogPackage.InserAC_OperateLog(opera, "UploadController文件上传");
                }
                //}
            }
            return(this.Json(result, JsonRequestBehavior.AllowGet));
        }
Exemple #20
0
        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();
        }
        /// <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('.'))));
        }
Exemple #22
0
        public ActionResult UploadImage()
        {
            Hashtable hash = new Hashtable();
            //long userId = Convert.ToInt64(Request["userId"]);
            //if (userId == 0)
            //{
            //    hash = new Hashtable();
            //    hash["error"] = 1;
            //    hash["message"] = "请先登录";
            //    return Json(hash, "text/html;charset=UTF-8");
            //}
            string savePath  = "/pic/AdminUpload/";
            string saveUrl   = "/pic/AdminUpload/";
            string fileTypes = "gif,jpg,jpeg,png,bmp";
            int    maxSize   = 1000000;

            HttpPostedFileBase file = Request.Files["imgFile"];

            if (file == null)
            {
                hash            = new Hashtable();
                hash["error"]   = 1;
                hash["message"] = "请选择文件";
                return(Json(hash));
            }

            string dirPath = Server.MapPath(savePath);

            if (!Directory.Exists(dirPath))
            {
                //hash = new Hashtable();
                //hash["error"] = 1;
                //hash["message"] = "上传目录不存在";
                //return Json(hash);
                System.IO.Directory.CreateDirectory(dirPath);
            }

            string fileName = file.FileName;
            string fileExt  = Path.GetExtension(fileName).ToLower();

            ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));

            if (file.InputStream == null || file.InputStream.Length > maxSize)
            {
                hash            = new Hashtable();
                hash["error"]   = 1;
                hash["message"] = "上传文件大小超过限制";
                return(Json(hash));
            }

            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                hash            = new Hashtable();
                hash["error"]   = 1;
                hash["message"] = "上传文件扩展名是不允许的扩展名";
                return(Json(hash));
            }

            #region wuyf 2015-7-22 注释 原来
            //string newFileName = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now) + fileExt;// 文件名称//DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            //string filePath = dirPath + newFileName;
            //file.SaveAs(filePath);
            //string fileUrl = saveUrl + newFileName;
            #endregion

            #region wuyf 2015-7-22
            int    _fileInfosize = (int)file.InputStream.Length;
            Stream stream        = file.InputStream;
            byte[] buffer        = new byte[_fileInfosize];
            stream.Read(buffer, 0, _fileInfosize);
            var t = Path.GetExtension(file.FileName);
            t = t == null ? "jpg" : t.Replace(".", "");
            string newFileName = FastDFSClient.UploadFile(FastDFSClient.DefaultGroup, buffer, t);
            string fileUrl     = ImagePath + newFileName;
            #endregion

            hash          = new Hashtable();
            hash["error"] = 0;
            hash["url"]   = fileUrl;

            return(Json(hash, "text/html;charset=UTF-8"));;
        }