Exemplo n.º 1
0
        public async Task <IEnumerable <FileItemViewModel> > GetPagedItemsAsync(int pageIndex, int pageSize, CancellationToken cancellationToken = new CancellationToken())
        {
            var pageResult = new List <FileItemViewModel>();

            if (pageIndex != 0 && string.IsNullOrEmpty(_marker))
            {
                return(pageResult);
            }

            var fetchResult = await QiniuService.GetFiles(_bucketName, _marker);

            _marker = fetchResult.Marker;
            if (fetchResult.Items == null || !fetchResult.Items.Any())
            {
                return(pageResult);
            }

            fetchResult.Items.ForEach(file =>
            {
                var fileObject = new FileObject
                {
                    FileName = file.Key,
                    MimeType = file.MimeType,
                    FileSize = file.Fsize,
                    PutTime  = file.PutTime
                };

                pageResult.Add(new FileItemViewModel
                {
                    FileObject = fileObject
                });
            });

            return(pageResult);
        }
Exemplo n.º 2
0
 public UploadController(QiniuService qiniuService,
                         UserStatuService userStatuService,
                         StorageService storageService) : base(userStatuService)
 {
     this._qiniuService   = qiniuService;
     this._storageService = storageService;
 }
Exemplo n.º 3
0
        public static string GrabPic(string imgUrl, bool isLocalHost = false)
        {
            string fileExt = string.Empty;
            string newUrl  = imgUrl;

            byte[] buffer   = Core.Utilities.HttpUtility.GetData(imgUrl, null, false);
            int    extIndex = imgUrl.LastIndexOf(".");

            fileExt = imgUrl.Substring(extIndex, imgUrl.Length - extIndex);
            using (MemoryStream target = new MemoryStream(buffer))
            {
                if (isLocalHost)
                {
                    newUrl = QiniuService.PutFileStringStream(target, "WX", fileExt);
                }
                else
                {
                    byte[] data     = target.ToArray();
                    string md5      = ToMd5String(data);
                    var    path     = @"Images\temp\";
                    var    fullPath = AppDomain.CurrentDomain.BaseDirectory + path;
                    if (!Directory.Exists(fullPath))
                    {
                        Directory.CreateDirectory(fullPath);
                    }
                    System.IO.File.WriteAllBytes(fullPath + md5 + fileExt, data);
                    newUrl = ConfigUtility.GetValue("QiNiuDomain") + md5 + fileExt;
                }
            }
            return(newUrl);
        }
Exemplo n.º 4
0
        public void ReturnThreadData(object state)
        {
            QiniuService service = state as QiniuService;

            result = service.Uploader.UploadFile(
                service.Filepath,
                service.Prefix + service.Savekey,
                service.Token);
            reset.Set();
        }
Exemplo n.º 5
0
 public AdminController(IHostingEnvironment env, QiniuService qiniuService,
                        IPostsRepository postsRepository, ICategoriesRepository categoriesRepository)
 {
     _qiniuService         = qiniuService;
     _categoriesRepository = categoriesRepository;
     _postsRepository      = postsRepository;
     _env = env;
     //HttpContext.User.Identity.Name
     //throw new Exception();
 }
Exemplo n.º 6
0
        private async Task CreateCommandExecute()
        {
            NotificationService.ShowMessage(ResourceUtils.GetText("BucketCreating"));
            var created = await QiniuService.CreateBucket(BucketObject) && await QiniuService.SetBucketAccessControl(BucketObject.Name, BucketObject.Private != "0");

            NotificationService.Dismiss();

            NotificationService.ShowMessage(
                created ? ResourceUtils.GetText("BucketCreatedSucceed") : ResourceUtils.GetText("BucketCreatedFailed"),
                2000);
        }
Exemplo n.º 7
0
        public ContentResult MuAdd(FormCollection form)
        {
            HttpFileCollectionBase files = Request.Files;

            //最大文件大小f
            int maxSize = 2048000;
            List <MyImageFormat> json = new List <MyImageFormat>();

            if (files.Count > 0)
            {
                try
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        if (files[i] == null)
                        {
                            continue;
                        }
                        string fileName = files[i].FileName;
                        string ext      = Path.GetExtension(fileName);
                        int    size     = files[i].ContentLength;

                        if (exts.Contains(ext) && files[i].InputStream != null && files[i].InputStream.Length <= maxSize)
                        {
                            files[i].InputStream.Position = 0;
                            using (Stream stream = files[i].InputStream)
                            {
                                string        imgUrl = QiniuService.PutFileStringStream(stream, "zhujia", ext);
                                MyImageFormat item   = new MyImageFormat()
                                {
                                    name = fileName,
                                    size = size,
                                    url  = imgUrl
                                };
                                json.Add(item);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(WriteJs(string.Format("UploadFailed('{0}')", ex.Message)));
                }
            }
            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            //ResizeSettings
            // ImageResizer
            string jsonData = jss.Serialize(json);

            return(WriteJs(string.Format("UploadComplete({0})", jsonData)));
        }
Exemplo n.º 8
0
 public AccountController(AppDbContext context,
                          QiniuService qiniuService,
                          UserManager <AppUser> userManager,
                          SignInManager <AppUser> signInManager,
                          IMailService mailService,
                          IHostingEnvironment env,
                          ILoggerFactory loggerFactory)
 {
     _qiniuService  = qiniuService;
     _context       = context;
     _env           = env;
     _userManager   = userManager;
     _signInManager = signInManager;
     _mailService   = mailService;
     _logger        = loggerFactory.CreateLogger <AccountController>();
 }
Exemplo n.º 9
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            _coreTitleBar.ExtendViewIntoTitleBar = true;
            Window.Current.SetTitleBar(TitleBarBackgroundElement);

            //notification
            NotificationService.Initialize(AppNotification);

            //main page datacontext
            var dataContext = new MainPageViewModel();

            DataContext = dataContext;

            //NaviagtionService Initialize
            NavigationService.MainFrame = ContentFrame;
            NavigationService.RegisterPageType("setting", typeof(SettingPage));
            NavigationService.RegisterPageType("files", typeof(FileListPage));
            NavigationService.RegisterPageType("create", typeof(CreateBucketPage));
            NavigationService.RegisterPageType("transfer", typeof(FileTransferPage));

            //Start File Transfer Service
            FileTransferService.Start();

            //load data
            var setting = AppSettingService.GetSetting();

            if (string.IsNullOrEmpty(setting.Ak) || string.IsNullOrEmpty(setting.Sk))
            {
                NavigationService.NaviageTo("setting");
            }
            else
            {
                QiniuService.Initialize(setting.Ak, setting.Sk);
                await dataContext.BucketListViewModel.Initialize();
            }
        }
Exemplo n.º 10
0
        public Crawler Fetch()
        {
            var request = HttpWebRequest.Create(this.SourceUrl) as HttpWebRequest;

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    State = "Url returns " + response.StatusCode + ", " + response.StatusDescription;
                    return(this);
                }
                if (response.ContentType.IndexOf("image") == -1)
                {
                    State = "Url is not an image";
                    return(this);
                }
                ServerUrl = PathFormatter.Format(Path.GetFileName(this.SourceUrl), Config.GetString("catcherPathFormat"));
                var savePath = Server.MapPath(ServerUrl);

                try
                {
                    var    stream = response.GetResponseStream();
                    var    reader = new BinaryReader(stream);
                    byte[] bytes;
                    using (var ms = new MemoryStream())
                    {
                        byte[] buffer = new byte[4096];
                        int    count;
                        while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            ms.Write(buffer, 0, count);
                        }
                        bytes = ms.ToArray();
                    }


                    string md5 = ToMd5String(bytes);
                    if (Request.Url.Host.Contains("localhost") || Request.UserHostAddress == "127.0.0.1")
                    {
                        string imgUrl = QiniuService.PutFile("WX", md5, bytes);


                        ServerUrl = imgUrl;
                        State     = "SUCCESS";
                    }
                    else
                    {
                        var path     = @"Images\temp\";
                        var fullPath = AppDomain.CurrentDomain.BaseDirectory + path;
                        if (!Directory.Exists(fullPath))
                        {
                            Directory.CreateDirectory(fullPath);
                        }
                        System.IO.File.WriteAllBytes(fullPath + md5 + ".jpg", bytes);
                        ServerUrl = ConfigUtility.GetValue("QiNiuDomain") + md5 + ".jpg";
                        State     = "SUCCESS";
                    }
                }
                catch (Exception e)
                {
                    State = "抓取错误:" + e.Message;
                }
                return(this);
            }
        }
Exemplo n.º 11
0
 public WeblogProvider(UserManager <AppUser> userMgr, IPostsRepository repo, QiniuService qiniuService)
 {
     _repo         = repo;
     _userMgr      = userMgr;
     _qiniuService = qiniuService;
 }
Exemplo n.º 12
0
 public QiniuStorageInfoController(QiniuService qiniuService)
 {
     this._qiniuService = qiniuService;
 }
Exemplo n.º 13
0
        public ActionResult uploadimage(FormCollection form)
        {
            string domain = ConfigUtility.GetValue("domain");


            //最大文件大小f
            int maxSize = 1000000;

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

            if (imgFile == null)
            {
                return(JsonReturnValue(new { Success = 0, imgurl = "", msg = "请选择文件" }, JsonRequestBehavior.AllowGet));
            }

            String fileName = imgFile.FileName;
            String fileExt  = Path.GetExtension(fileName);

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                return(JsonReturnValue(new { Success = 0, imgurl = "", msg = "上传文件大小超过限制" }, JsonRequestBehavior.AllowGet));
            }

            if (!exts.Contains(fileExt))
            {
                return(JsonReturnValue(new { Success = 0, imgurl = "", msg = "上传文件扩展名是不允许的扩展名。\n只允许" + (exts.Aggregate((a, b) => a + ", " + b)) + "格式" }, JsonRequestBehavior.AllowGet));
            }


            imgFile.InputStream.Position = 0;


            imgFile.InputStream.Position = 0;
            MemoryStream target = new MemoryStream();

            imgFile.InputStream.CopyTo(target);

            byte[] data = target.ToArray();
            #region 水印

            int pos = 0;
            if (form["wmPos"] != null && form["wmPos"].ToString() != "")//有设置水印
            {
                int.TryParse(form["wmPos"].ToString(), out pos);
            }
            if (pos > 0)
            {
                if (form["wmUrl"] != null && form["wmUrl"].ToString() != "")//有水印图片
                {
                    string wmUrl  = form["wmUrl"].ToString();
                    string ioPath = this.HttpContext.Server.MapPath(wmUrl);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(target);
                    if (image.Width < 300 || image.Height < 200)
                    {
                        return(JsonReturnValue(new { Success = 0, imgurl = "", msg = "添加水印时尺寸不能小于300*200" }, JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(wmUrl) && System.IO.File.Exists(ioPath))
                        {
                            data = addWaterMark(image, ioPath, (WaterPositionMode)pos);
                        }
                    }
                }
            }
            #endregion

            string md5 = ToMd5String(data);


            string imgUrl = QiniuService.PutFile("zhujia", md5 + fileExt, data);
            return(JsonReturnValue(new { Success = 0, imgurl = imgUrl, msg = "上传成功" }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 14
0
 public UploadController(QiniuService qiniuService)
 {
     _qiniuService = qiniuService;
 }
Exemplo n.º 15
0
        public ContentResult Add(FormCollection form)
        {
            string domain    = ConfigUtility.GetValue("domain");
            string imageType = form["imageType"];

            //最大文件大小f
            int maxSize = 1000000;

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

            if (imgFile == null)
            {
                return(Content("<script>document.domain='" + domain + "';parent.callback('" + imageType + "', '请选择文件。', null);</script>"));
            }

            String fileName = imgFile.FileName;
            String fileExt  = Path.GetExtension(fileName);

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                return(Content("<script>parent.callback(''" + imageType + "'', '上传文件大小超过限制。', null);</script>"));
            }

            if (!exts.Contains(fileExt))
            {
                return(Content("<script>parent.callback(''" + imageType + "'', '上传文件扩展名是不允许的扩展名。\n只允许" + (exts.Aggregate((a, b) => a + ", " + b)) + "格式', null);</script>"));
            }


            imgFile.InputStream.Position = 0;
            //if (Request.Url.Host.Contains("localhost") || Request.UserHostAddress == "127.0.0.1")
            //{
            //    using (Stream stream = imgFile.InputStream)
            //    {
            //    string imgUrl = QiniuService.PutFileStringStream(stream, "WX", fileExt);
            //        return Content("<script>parent.callback(''" + imageType + "'', '" + imgUrl + "', null);</script>");
            //    }
            //}
            //imgFile.InputStream.Position = 0;
            //MemoryStream target = new MemoryStream();
            //imgFile.InputStream.CopyTo(target);

            //byte[] data = target.ToArray();
            //#region 水印

            //int pos = 0;
            //if (form["wmPos"] != null && form["wmPos"].ToString() != "")///有设置水印
            //{
            //    int.TryParse(form["wmPos"].ToString(), out pos);
            //}
            //if (pos > 0)
            //{
            //    if (form["wmUrl"] != null && form["wmUrl"].ToString() != "")///有水印图片
            //    {
            //        string wmUrl = form["wmUrl"].ToString();
            //        string ioPath = this.HttpContext.Server.MapPath(wmUrl);
            //        System.Drawing.Image image = System.Drawing.Image.FromStream(target);
            //        if (image.Width < 300 || image.Height < 200)
            //        {
            //            return Content("<script>parent.alert(''" + imageType + "'', '添加水印时尺寸不能小于300*200!', null);</script>");
            //        }
            //        else
            //        {
            //            if (!string.IsNullOrEmpty(wmUrl) && System.IO.File.Exists(ioPath))
            //            {
            //                data = addWaterMark(image, ioPath, (WaterPositionMode)pos);
            //            }
            //        }
            //    }
            //}
            //#endregion
            //string md5 = ToMd5String(data);
            //var path = @"Images\temp\";
            //var fullPath = AppDomain.CurrentDomain.BaseDirectory + path;
            //if (!Directory.Exists(fullPath))
            //    Directory.CreateDirectory(fullPath);
            //System.IO.File.WriteAllBytes(fullPath + md5 + fileExt, data);
            //return Content("<script>parent.callback('" + imageType + "', '"
            //    + ConfigUtility.GetValue("QiNiuDomain") + md5 + fileExt + "', null);</script>");


            imgFile.InputStream.Position = 0;
            MemoryStream target = new MemoryStream();

            imgFile.InputStream.CopyTo(target);

            byte[] data = target.ToArray();
            #region 水印

            int pos = 0;
            if (form["wmPos"] != null && form["wmPos"].ToString() != "")///有设置水印
            {
                int.TryParse(form["wmPos"].ToString(), out pos);
            }
            if (pos > 0)
            {
                if (form["wmUrl"] != null && form["wmUrl"].ToString() != "")///有水印图片
                {
                    string wmUrl  = form["wmUrl"].ToString();
                    string ioPath = this.HttpContext.Server.MapPath(wmUrl);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(target);
                    if (image.Width < 300 || image.Height < 200)
                    {
                        return(Content("<script>parent.alert(''" + imageType + "'', '添加水印时尺寸不能小于300*200!', null);</script>"));
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(wmUrl) && System.IO.File.Exists(ioPath))
                        {
                            data = addWaterMark(image, ioPath, (WaterPositionMode)pos);
                        }
                    }
                }
            }
            #endregion

            string md5 = ToMd5String(data);



            using (Stream stream = new MemoryStream(data))
            {
                string imgUrl = QiniuService.PutFileStringStream(stream, "zhujia", fileExt);
                return(Content("<script>parent.callback(''" + imageType + "'', '" + imgUrl + "', null);</script>"));
            }
        }
Exemplo n.º 16
0
 public QiniuCallBackController(QiniuService qiniuService)
 {
     this._qiniuService = qiniuService;
 }
Exemplo n.º 17
0
 public QiniuUploadController(QiniuService qiniuService,
                              UserStatuService userStatuService) : base(userStatuService)
 {
     this._qiniuService = qiniuService;
 }
Exemplo n.º 18
0
    public override void Process()
    {
        byte[] uploadFileBytes = null;
        string uploadFileName  = null;

        if (UploadConfig.Base64)
        {
            uploadFileName  = UploadConfig.Base64Filename;
            uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]);
        }
        else
        {
            var file = Request.Files[UploadConfig.UploadFieldName];
            uploadFileName = file.FileName;

            if (!CheckFileType(uploadFileName))
            {
                Result.State = UploadState.TypeNotAllow;
                WriteResult();
                return;
            }
            if (!CheckFileSize(file.ContentLength))
            {
                Result.State = UploadState.SizeLimitExceed;
                WriteResult();
                return;
            }

            uploadFileBytes = new byte[file.ContentLength];
            try
            {
                file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
            }
            catch (Exception)
            {
                Result.State = UploadState.NetworkError;
                WriteResult();
            }
        }

        Result.OriginFileName = uploadFileName;

        var savePath  = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);
        var localPath = Server.MapPath(savePath);

        try
        {
            //if (!Directory.Exists(Path.GetDirectoryName(localPath)))
            //{
            //    Directory.CreateDirectory(Path.GetDirectoryName(localPath));
            //}
            //File.WriteAllBytes(localPath, uploadFileBytes);
            //Result.Url = savePath;
            //Result.State = UploadState.Success;

            string md5 = ToMd5String(uploadFileBytes);
            if (Request.Url.Host.Contains("localhost") || Request.UserHostAddress == "127.0.0.1")
            {
                string imgUrl = QiniuService.PutFile("WX", md5, uploadFileBytes);
                Result.Url   = imgUrl;
                Result.State = UploadState.Success;
            }
            else
            {
                var path     = @"Images\temp\";
                var fullPath = AppDomain.CurrentDomain.BaseDirectory + path;
                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }
                System.IO.File.WriteAllBytes(fullPath + md5 + ".jpg", uploadFileBytes);
                Result.Url   = ConfigUtility.GetValue("QiNiuDomain") + md5 + ".jpg";
                Result.State = UploadState.Success;
            }
        }
        catch (Exception e)
        {
            Result.State        = UploadState.FileAccessError;
            Result.ErrorMessage = e.Message;
        }
        finally
        {
            WriteResult();
        }
    }
Exemplo n.º 19
0
 private string UploadQiNiu(byte[] byteImgs)
 {
     return(AppSettings.QiNiuConfig.ImgUrl + QiniuService.UploadImg(byteImgs));
 }