Пример #1
0
        public async Task <JsonResult> UploadLogo()
        {
            try
            {
                var logoFile = Request.Form.Files.First();

                //Check input
                if (logoFile == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                if (logoFile.Length > 30720) //30KB
                {
                    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                }

                byte[] fileBytes;
                using (var stream = logoFile.OpenReadStream())
                {
                    fileBytes = stream.GetAllBytes();
                }

                var imageFormat = ImageFormatHelper.GetRawImageFormat(fileBytes);
                if (!imageFormat.IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif))
                {
                    throw new UserFriendlyException("File_Invalid_Type_Error");
                }

                var logoObject = new BinaryObject(AbpSession.GetTenantId(), fileBytes);
                await _binaryObjectManager.SaveAsync(logoObject);

                var tenant = await _tenantManager.GetByIdAsync(AbpSession.GetTenantId());

                tenant.LogoId       = logoObject.Id;
                tenant.LogoFileType = logoFile.ContentType;

                return(Json(new AjaxResponse(new { id = logoObject.Id, fileType = tenant.LogoFileType })));
            }
            catch (UserFriendlyException ex)
            {
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }
        public async Task UpdateProfilePicture(UpdateProfilePictureInput input)
        {
            var tempProfilePicturePath = Path.Combine(_appFolders.TempFileDownloadFolder, input.FileName);

            byte[] byteArray;

            using (var fsTempProfilePicture = new FileStream(tempProfilePicturePath, FileMode.Open))
            {
                using (var bmpImage = new Bitmap(fsTempProfilePicture))
                {
                    var width  = input.Width == 0 ? bmpImage.Width : input.Width;
                    var height = input.Height == 0 ? bmpImage.Height : input.Height;
                    var bmCrop = bmpImage.Clone(new Rectangle(input.X, input.Y, width, height), bmpImage.PixelFormat);

                    using (var stream = new MemoryStream())
                    {
                        bmCrop.Save(stream, bmpImage.RawFormat);
                        stream.Close();
                        byteArray = stream.ToArray();
                    }
                }
            }

            if (byteArray.LongLength > 102400) //100 KB
            {
                throw new UserFriendlyException(L("ResizedProfilePicture_Warn_SizeLimit"));
            }

            var user = await UserManager.GetUserByIdAsync(AbpSession.GetUserId());

            if (user.ProfilePictureId.HasValue)
            {
                await _binaryObjectManager.DeleteAsync(user.ProfilePictureId.Value);
            }

            var storedFile = new BinaryObject(AbpSession.TenantId, byteArray);
            await _binaryObjectManager.SaveAsync(storedFile);

            user.ProfilePictureId = storedFile.Id;

            FileHelper.DeleteIfExists(tempProfilePicturePath);
        }
Пример #3
0
        public async Task <JsonResult> UploadFile()
        {
            string error = "", fileName = "";
            string path = "";
            Guid   name = Guid.Empty;
            var    host = _options.Value.ClientRootAddress;

            try
            {
                var    oFile = Request.Form.Files["txt_file"];
                Stream sm    = oFile.OpenReadStream();
                fileName = oFile.FileName;
                var user   = AbpSession.UserId?.ToString() ?? "zero";
                var folder = $"{AppContext.BaseDirectory}/{user}/{DateTime.Now:yyyyMMdd}/";

                var ext = oFile.FileName.Split('.').Last();
                name = Guid.NewGuid();
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                string filename = $"{folder}{name.ToString()}.{ext}";
                ;
                FileStream fs     = new FileStream(filename, FileMode.Create);
                var        length = sm.Length;
                byte[]     buffer = new byte[length];
                sm.Read(buffer, 0, buffer.Length);
                fs.Write(buffer, 0, buffer.Length);
                fs.Dispose();
                path = $"/{user}/{DateTime.Now:yyyyMMdd}/{name.ToString()}.{ext}";
                //保存数据库
                await _storager.SaveAsync(new BinaryObject()
                {
                    Id     = name,
                    Name   = filename,
                    Size   = length,
                    Suffix = ext,
                    Url    = path
                });
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            return(Json(new
            {
                result = !string.IsNullOrWhiteSpace(error),
                fileName = fileName,
                url = path,
                viewUrl = host + path,
                guid = name
            }));
        }
Пример #4
0
        public async Task UpdateProfilePicture(UpdateProfilePictureInput input)
        {
            await SettingManager.ChangeSettingForUserAsync(
                AbpSession.ToUserIdentifier(),
                AppSettings.UserManagement.UseGravatarProfilePicture,
                input.UseGravatarProfilePicture.ToString().ToLowerInvariant()
                );

            if (input.UseGravatarProfilePicture)
            {
                return;
            }

            byte[] byteArray;

            var imageBytes = _tempFileCacheManager.GetFile(input.FileToken);

            if (imageBytes == null)
            {
                throw new UserFriendlyException("There is no such image file with the token: " + input.FileToken);
            }

            using (var bmpImage = new Bitmap(new MemoryStream(imageBytes)))
            {
                var width  = (input.Width == 0 || input.Width > bmpImage.Width) ? bmpImage.Width : input.Width;
                var height = (input.Height == 0 || input.Height > bmpImage.Height) ? bmpImage.Height : input.Height;
                var bmCrop = bmpImage.Clone(new Rectangle(input.X, input.Y, width, height), bmpImage.PixelFormat);

                using (var stream = new MemoryStream())
                {
                    bmCrop.Save(stream, bmpImage.RawFormat);
                    byteArray = stream.ToArray();
                }
            }

            if (byteArray.Length > MaxProfilPictureBytes)
            {
                throw new UserFriendlyException(L("ResizedProfilePicture_Warn_SizeLimit",
                                                  AppConsts.ResizedMaxProfilPictureBytesUserFriendlyValue));
            }

            var user = await UserManager.GetUserByIdAsync(AbpSession.GetUserId());

            if (user.ProfilePictureId.HasValue)
            {
                await _binaryObjectManager.DeleteAsync(user.ProfilePictureId.Value);
            }

            var storedFile = new BinaryObject(AbpSession.TenantId, byteArray);
            await _binaryObjectManager.SaveAsync(storedFile);

            user.ProfilePictureId = storedFile.Id;
        }
Пример #5
0
        public async Task <JsonResult> UploadLogo()
        {
            try
            {
                if (Request.Files.Count <= 0 || Request.Files[0] == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                var file = Request.Files[0];

                if (file.ContentLength > 30720) //30KB
                {
                    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                }

                var fileBytes = file.InputStream.GetAllBytes();

                if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif))
                {
                    throw new UserFriendlyException("File_Invalid_Type_Error");
                }

                var logoObject = new BinaryObject(AbpSession.GetTenantId(), fileBytes);
                await _binaryObjectManager.SaveAsync(logoObject);

                var tenant = await _tenantManager.GetByIdAsync(AbpSession.GetTenantId());

                tenant.LogoId       = logoObject.Id;
                tenant.LogoFileType = file.ContentType;

                return(Json(new AjaxResponse(new { id = logoObject.Id, fileType = tenant.LogoFileType })));
            }
            catch (UserFriendlyException ex)
            {
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }
Пример #6
0
        //[AbpAuthorize(PermissionNames.Administration_Facilities_Manage)]
        public async Task <UpdateProfilePictureOutput> UpdateIconPicture(UpdateProfilePictureInput input)
        {
            var tenant = await _tenantManager.FindByIdAsync(input.TenantId);

            if (tenant == null)
            {
                throw new UserFriendlyException(L("InvalidAction"));
            }

            byte[] data;
            using (var ms = new MemoryStream())
            {
                var newWidth  = input.Width;
                var newHeight = input.Height;

                using (var newImg = new Bitmap(newWidth, newHeight))
                {
                    var fullPath = Path.Combine(Path.GetTempPath(), input.FileName);
                    using (var img = Image.FromFile(fullPath))
                        using (var g = Graphics.FromImage(newImg))
                        {
                            g.DrawImage(img,
                                        new Rectangle(0, 0, newWidth, newHeight),
                                        new Rectangle(input.X, input.Y, input.Width, input.Height),
                                        GraphicsUnit.Pixel);
                        }
                    newImg.Save(ms, ImageFormat.Jpeg);
                }

                data = ms.ToArray();
            }

            var binaryObjectId = await _binaryObjectManager.SaveAsync(BinaryObjectTypes.TenantProfilePicture, data, "image/jpeg");

            if (tenant.ProfilePictureId != null)
            {
                await _binaryObjectManager.DeleteAsync(tenant.ProfilePictureId.Value, BinaryObjectTypes.TenantProfilePicture);
            }

            tenant.UpdateProfilePicture(binaryObjectId);
            await _tenantManager.UpdateAsync(tenant);

            return(new UpdateProfilePictureOutput
            {
                TenantId = tenant.Id,
                ProfilePictureId = tenant.ProfilePictureId
            });
        }
Пример #7
0
        private async Task SetRandomProfilePictureAsync(User user)
        {
            try
            {
                var binaryObject = new BinaryObject(GetRandomProfilePictureBytes());
                await _binaryObjectManager.SaveAsync(binaryObject);

                user.ProfilePictureId = new Guid?(binaryObject.Id);
                await CurrentUnitOfWork.SaveChangesAsync();

                binaryObject = null;
            }
            catch
            {
            }
        }
        private async Task SetRandomProfilePictureAsync(User user)
        {
            try
            {
                //Save a random profile picture
                var storedFile = new BinaryObject(user.TenantId, GetRandomProfilePictureBytes());
                await _binaryObjectManager.SaveAsync(storedFile);

                //Update new picture on the user
                user.ProfilePictureId = storedFile.Id;
                await CurrentUnitOfWork.SaveChangesAsync();
            }
            catch
            {
                //we can ignore this exception
            }
        }
        public override async Task ExecuteAsync(UserIdentifier args)
        {
            using (UnitOfWorkManager.Current.SetTenantId(args.TenantId))
            {
                var userLanguage = await _settingManager.GetSettingValueForUserAsync(
                    LocalizationSettingNames.DefaultLanguage,
                    args.TenantId,
                    args.UserId
                    );

                var culture = CultureHelper.GetCultureInfoByChecking(userLanguage);

                using (CultureInfoHelper.Use(culture))
                {
                    var files = new List <FileDto>();

                    using (var scope = IocManager.Instance.CreateScope())
                    {
                        var providers = scope.ResolveAll <IUserCollectedDataProvider>();
                        foreach (var provider in providers)
                        {
                            var providerFiles = await provider.GetFiles(args);

                            if (providerFiles.Any())
                            {
                                files.AddRange(providerFiles);
                            }
                        }
                    }

                    var zipFile = new BinaryObject
                                  (
                        args.TenantId,
                        CompressFiles(files),
                        $"{args.UserId} {DateTime.UtcNow} UserCollectedDataPrepareJob result"
                                  );

                    // Save zip file to object manager.
                    await _binaryObjectManager.SaveAsync(zipFile);

                    // Send notification to user.
                    await _appNotifier.GdprDataPrepared(args, zipFile.Id);
                }
            }
        }
Пример #10
0
        public async Task <JsonResult> UploadFiles()
        {
            try
            {
                var files = Request.Form.Files;

                //Check input
                if (files == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                List <UploadFileOutput> filesOutput = new List <UploadFileOutput>();

                foreach (var file in files)
                {
                    if (file.Length > 1048576) //1MB
                    {
                        throw new UserFriendlyException(L("File_SizeLimit_Error"));
                    }

                    byte[] fileBytes;
                    using (var stream = file.OpenReadStream())
                    {
                        fileBytes = stream.GetAllBytes();
                    }

                    var fileObject = new BinaryObject(AbpSession.TenantId, fileBytes, $"Demo ui, uploaded file {DateTime.UtcNow}");
                    await _binaryObjectManager.SaveAsync(fileObject);

                    filesOutput.Add(new UploadFileOutput
                    {
                        Id       = fileObject.Id,
                        FileName = file.FileName
                    });
                }

                return(Json(new AjaxResponse(filesOutput)));
            }
            catch (UserFriendlyException ex)
            {
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }
Пример #11
0
        public async Task <string> SaveImages()
        {
            HttpPostedFile file = HttpContext.Current.Request.Files["file02"];//接收

            byte[] byteArray;
            //Save new picture
            var fileInfo     = new FileInfo(file.FileName);
            var tempFileName = "androidImage_" + file.FileName;  /*+fileInfo.Extension*/
            var tempFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, tempFileName);

            file.SaveAs(tempFilePath);

            //if (!File.Exists(tempFilePath))//判断文件是否存在
            //{//若不存在
            //    Directory.CreateDirectory(tempFilePath);//这个方法创建文件夹的时候如果文件夹存在的话就不会创建了,所以不管文件有没有都调用一下,省得写那么多判断
            //    file.SaveAs(tempFilePath); //保存文件
            //}

            using (var fsTempProfilePicture = new FileStream(tempFilePath, FileMode.Open))
            {
                using (var bmpImage = new Bitmap(fsTempProfilePicture))
                {
                    //var width = input.Width == 0 ? bmpImage.Width : input.Width;
                    //var height = input.Height == 0 ? bmpImage.Height : input.Height;
                    //var bmCrop = bmpImage.Clone(new Rectangle(input.X, input.Y, width, height), bmpImage.PixelFormat);

                    using (var stream = new MemoryStream())
                    {
                        bmpImage.Save(stream, bmpImage.RawFormat);
                        stream.Close();
                        byteArray = stream.ToArray();
                    }
                }
            }

            //if (byteArray.LongLength > 102400) //100 KB
            //{
            //    throw new UserFriendlyException(L("ResizedProfilePicture_Warn_SizeLimit"));
            //}
            var storedFile = new BinaryObject(AbpSession.TenantId, byteArray);
            await _binaryObjectManager.SaveAsync(storedFile);

            return(tempFilePath); //返回MD5码,用于后面保存在数据库
        }
Пример #12
0
        public async Task <JsonResult> UploadFile()
        {
            try
            {
                var file = Request.Form.Files.First();

                //Check input
                if (file == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                if (file.Length > 10000000) //10MB
                {
                    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                }

                byte[] fileBytes;
                using (var stream = file.OpenReadStream())
                {
                    fileBytes = stream.GetAllBytes();
                }

                var fileObject = new BinaryObject(null, fileBytes);
                using (CurrentUnitOfWork.SetTenantId(null))
                {
                    await BinaryObjectManager.SaveAsync(fileObject);

                    await CurrentUnitOfWork.SaveChangesAsync();
                }

                return(Json(new AjaxResponse(new
                {
                    id = fileObject.Id,
                    name = file.FileName,
                    contentType = file.ContentType
                })));
            }
            catch (UserFriendlyException ex)
            {
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }
Пример #13
0
        private async Task <System.Guid> StoreProfilePicture(string filename)
        {
            var tempProfilePicturePath = Path.Combine(_appFolders.TempFileDownloadFolder, filename);

            byte[] byteArray = File.ReadAllBytes(tempProfilePicturePath);

            if (byteArray.Length > MaxProfilPictureBytes)
            {
                throw new UserFriendlyException(L("ResizedProfilePicture_Warn_SizeLimit", AppConsts.ResizedMaxProfilPictureBytesUserFriendlyValue));
            }

            var storedFile = new BinaryObject(AbpSession.TenantId, byteArray);

            await _binaryObjectManager.SaveAsync(storedFile);

            FileHelper.DeleteIfExists(tempProfilePicturePath);

            return(storedFile.Id);
        }
Пример #14
0
        public async Task <JsonResult> ImportFromExcel()
        {
            try
            {
                var file = Request.Form.Files.First();

                if (file == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                if (file.Length > 1048576 * 100) //100 MB
                {
                    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                }

                byte[] fileBytes;
                using (var stream = file.OpenReadStream())
                {
                    fileBytes = stream.GetAllBytes();
                }

                var tenantId   = AbpSession.TenantId;
                var fileObject = new BinaryObject(tenantId, fileBytes);


                BinaryObjectManager.SaveAsync(fileObject);
                CurrentUnitOfWork.SaveChanges();

                await BackgroundJobManager.EnqueueAsync <ImportUsersToExcelJob, ImportUsersFromExcelJobArgs>(new ImportUsersFromExcelJobArgs
                {
                    TenantId       = tenantId,
                    BinaryObjectId = fileObject.Id,
                    User           = AbpSession.ToUserIdentifier()
                });

                return(Json(new AjaxResponse(new { })));
            }
            catch (UserFriendlyException ex)
            {
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }
Пример #15
0
        /// <summary>
        /// 下载保存多媒体文件,返回多媒体保存路径
        /// </summary>
        /// <param name="media"></param>
        /// <returns></returns>
        private async Task <Guid> GetMultimedia(string media)
        {
            var token = await GetTokenFromCache();

            string url =
                $"https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token={token}&media_id={media}";
            Guid   name   = Guid.NewGuid();
            var    path   = "/Files/Wechat/";
            string ext    = string.Empty;
            Stream stream = DownLoadFielToMemoryStream(url, out ext);

            if (stream != null)
            {
                var    length = stream.Length;
                string fp     = Path.Combine(_appFolders.ImageFolder, "WeChat/");
                if (!Directory.Exists(fp))
                {
                    Directory.CreateDirectory(fp);
                }
                var temp     = $"{name:N}.{ext}";
                var filepath = Path.Combine(fp, temp);
                using (var fileStream = File.Create(filepath))
                {
                    byte[] buffer    = new byte[1024];
                    int    bytesRead = 0;
                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        fileStream.Write(buffer, 0, bytesRead);
                    }
                    fileStream.Flush();
                }
                stream.Close();
                await _objectManager.SaveAsync(new BinaryObject()
                {
                    Id     = name,
                    Name   = temp,
                    Url    = path + temp,
                    Suffix = "." + ext,
                    Size   = length
                });
            }
            return(name);
        }
Пример #16
0
        public virtual async Task <JsonResult> ChangeProfilePicture()
        {
            try
            {
                //Check input
                if (Request.Files.Count <= 0 || Request.Files[0] == null)
                {
                    throw new UserFriendlyException(L("ProfilePicture_Change_Error"));
                }

                var file = Request.Files[0];

                if (file.ContentLength > 30720) //30KB.
                {
                    throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit"));
                }

                //Get user
                var user = await _userManager.GetUserByIdAsync(AbpSession.GetUserId());

                //Delete old picture
                if (user.ProfilePictureId.HasValue)
                {
                    await _binaryObjectManager.DeleteAsync(user.ProfilePictureId.Value);
                }

                //Save new picture
                var storedFile = new BinaryObject(AbpSession.TenantId, file.InputStream.GetAllBytes());
                await _binaryObjectManager.SaveAsync(storedFile);

                //Update new picture on the user
                user.ProfilePictureId = storedFile.Id;

                //Return success
                return(Json(new AjaxResponse()));
            }
            catch (UserFriendlyException ex)
            {
                //Return error message
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }
Пример #17
0
        private async Task <byte[]> UpdateCompanyLogo(TenantExtendedUnitInput input)
        {
            var tempProfilePicturePath = Path.Combine(_appFolders.TempFileDownloadFolder, input.ComapanyLogo.FileName);

            byte[] byteArray;

            using (var fsTempProfilePicture = new FileStream(tempProfilePicturePath, FileMode.Open))
            {
                using (var bmpImage = new Bitmap(fsTempProfilePicture))
                {
                    var width  = input.ComapanyLogo.Width == 0 ? bmpImage.Width : input.ComapanyLogo.Width;
                    var height = input.ComapanyLogo.Height == 0 ? bmpImage.Height : input.ComapanyLogo.Height;
                    var bmCrop = bmpImage.Clone(new Rectangle(input.ComapanyLogo.X, input.ComapanyLogo.Y, width, height), bmpImage.PixelFormat);

                    using (var stream = new MemoryStream())
                    {
                        bmCrop.Save(stream, bmpImage.RawFormat);
                        stream.Close();
                        byteArray = stream.ToArray();
                    }
                }
            }

            if (byteArray.LongLength > 1024000) //1000 KB
            {
                throw new UserFriendlyException(L("ResizedProfilePicture_Warn_SizeLimit"));
            }


            if (input.CompanyLogoId.HasValue)
            {
                await _binaryObjectManager.DeleteAsync(input.CompanyLogoId.Value);
            }

            var storedFile = new BinaryObject(AbpSession.TenantId, byteArray);
            await _binaryObjectManager.SaveAsync(storedFile);

            input.CompanyLogoId = storedFile.Id;
            return(byteArray);
        }
Пример #18
0
        public override void Execute(UserIdentifier args)
        {
            using (UnitOfWorkManager.Current.SetTenantId(args.TenantId))
            {
                var userLanguage = AsyncHelper.RunSync(() => _settingManager.GetSettingValueForUserAsync(LocalizationSettingNames.DefaultLanguage, args.TenantId, args.UserId));
                var culture      = CultureHelper.GetCultureInfoByChecking(userLanguage);

                using (CultureInfoHelper.Use(culture))
                {
                    var files = new List <FileDto>();

                    using (var scope = IocManager.Instance.CreateScope())
                    {
                        var providers = scope.ResolveAll <IUserCollectedDataProvider>();
                        foreach (var provider in providers)
                        {
                            var providerFiles = AsyncHelper.RunSync(() => provider.GetFiles(args));
                            if (providerFiles.Any())
                            {
                                files.AddRange(providerFiles);
                            }
                        }
                    }

                    var zipFile = new BinaryObject
                    {
                        TenantId = args.TenantId,
                        Bytes    = CompressFiles(files)
                    };

                    // Save zip file to object manager.
                    _binaryObjectManager.SaveAsync(zipFile);
                    //AsyncHelper.RunSync(() => );

                    // Send notification to user.
                    AsyncHelper.RunSync(() => _appNotifier.GdprDataPrepared(args, zipFile.Id));
                }
            }
        }
Пример #19
0
        public async Task <JsonResult> UploadFile(string DefaultFileUploadTextInput)
        {
            try
            {
                var file = Request.Form.Files.First();

                //Check input
                if (file == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                if (file.Length > 1048576) //1MB
                {
                    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                }

                byte[] fileBytes;
                using (var stream = file.OpenReadStream())
                {
                    fileBytes = stream.GetAllBytes();
                }

                var fileObject = new BinaryObject(null, fileBytes, "");
                await _binaryObjectManager.SaveAsync(fileObject);

                return(Json(new AjaxResponse(new
                {
                    id = fileObject.Id,
                    contentType = file.ContentType,
                    defaultFileUploadTextInput = DefaultFileUploadTextInput
                })));
            }
            catch (UserFriendlyException ex)
            {
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }
Пример #20
0
        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateHeadImage(UpdateHeadImageInput input)
        {
            string fixedFilePath = String.Empty, absoluteFilePath = String.Empty;
            string absolutePath = "/AppData/FileUpload/Image/HeadImage/";
            string fixedPath    = _environment.ContentRootPath + absolutePath;
            var    imageBytes   = _tempFileCacheManager.GetFile(input.FileToken);

            if (imageBytes == null)
            {
                throw new UserFriendlyException("There is no such image file with the token: " + input.FileToken);
            }
            using (var bmpImage = new Bitmap(new MemoryStream(imageBytes)))
            {
                var width  = (input.Width == 0 || input.Width > bmpImage.Width) ? bmpImage.Width : input.Width;
                var height = (input.Height == 0 || input.Height > bmpImage.Height) ? bmpImage.Height : input.Height;
                var bmCrop = bmpImage.Clone(new Rectangle(input.X, input.Y, width, height), bmpImage.PixelFormat);
                // TODO:限制裁剪后图片大小 1、先将图片保存成流 2、判断大小 3、大了结束。小了再将流保存成图片
                if (!Directory.Exists(fixedPath))
                {
                    Directory.CreateDirectory(fixedPath);
                }
                absoluteFilePath = absolutePath + input.FileToken + ".jpg";
                fixedFilePath    = fixedPath + input.FileToken + ".jpg";
                bmCrop.Save(fixedFilePath, bmpImage.RawFormat);
            }

            User user = await UserManager.GetUserByIdAsync(AbpSession.GetUserId());

            if (user.ProfilePictureId.HasValue)
            {
                await _binaryObjectManager.DeleteAsync(user.ProfilePictureId.Value);
            }

            var storedFile = new BinaryObject(AbpSession.TenantId, absoluteFilePath);
            await _binaryObjectManager.SaveAsync(storedFile);

            user.ProfilePictureId = storedFile.Id;
        }
Пример #21
0
        public async Task <AjaxResponse> ImageUpload()
        {
            var result = new List <object>();

            try
            {
                // 是否请求包含multipart/form-data。
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }
                var provider = new MultipartFormDataStreamProvider(_appFolders.ImageFolder);
                // 阅读表格数据并返回一个异步任务.
                await Request.Content.ReadAsMultipartAsync(provider);

                // 如何上传文件到文件名.
                foreach (var file in provider.FileData)
                {
                    var orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
                    var fileinfo   = new FileInfo(file.LocalFileName);
                    //最大文件大小
                    const int maxSize = 10000000;
                    if (fileinfo.Length <= 0)
                    {
                        throw new  UserFriendlyException("请选择上传的文件");
                    }
                    if (fileinfo.Length > maxSize)
                    {
                        throw new UserFriendlyException("上传文件大小超过限制");
                    }
                    string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
                    // 定义允许上传的文件扩展名
                    if (string.IsNullOrEmpty(fileExt) || Array.IndexOf("png,jpeg,jpg,gif,bmp".Split(','), fileExt.Substring(1).ToLower()) == -1)
                    {
                        throw new UserFriendlyException("图片类型不正确");
                    }
                    var ymd      = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                    var p        = AbpSession.UserId?.ToString() ?? "total";
                    var pathName = $"{p}/{ymd}";
                    var temp     = Path.Combine(_appFolders.ImageFolder, pathName);
                    if (!Directory.Exists(temp))
                    {
                        Directory.CreateDirectory(temp);
                    }
                    var guid     = Guid.NewGuid();
                    var fileName = guid + fileExt;
                    fileinfo.CopyTo(Path.Combine(temp, fileName), true);
                    var url = $"/Files/Images/{pathName}/{fileName}";
                    //保存文件
                    await _binaryObjectManager.SaveAsync(new BinaryObject()
                    {
                        Id     = guid,
                        Url    = url,
                        Size   = fileinfo.Length,
                        Suffix = fileExt,
                        Name   = orfilename
                    });

                    result.Add(new
                    {
                        code    = 1,
                        guid    = guid,
                        viewUrl = Host + url,
                        size    = fileinfo.Length,
                        suffix  = fileExt,
                        name    = orfilename
                    });
                    fileinfo.Delete();//删除原文件
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(new AjaxResponse(result));
        }