/// <summary> /// Check whether there are any restrictions on handling the file /// </summary> /// <param name="path">Path to the file</param> /// <returns>True if the file can be handled; otherwise false</returns> protected virtual bool CanHandleFile(string path) { var result = false; var fileExtension = _fileProvider.GetFileExtension(path).Replace(".", string.Empty).ToLower(); var forbiddenUploads = GetSetting("FORBIDDEN_UPLOADS").Trim().ToLower(); if (!string.IsNullOrEmpty(forbiddenUploads)) { var forbiddenFileExtensions = new ArrayList(Regex.Split(forbiddenUploads, "\\s+")); result = !forbiddenFileExtensions.Contains(fileExtension); } var allowedUploads = GetSetting("ALLOWED_UPLOADS").Trim().ToLower(); if (string.IsNullOrEmpty(allowedUploads)) { return(result); } var allowedFileExtensions = new ArrayList(Regex.Split(allowedUploads, "\\s+")); result = allowedFileExtensions.Contains(fileExtension); return(result); }
/// <summary> /// Gets the default picture URL /// </summary> /// <param name="targetSize">The target picture size (longest side)</param> /// <param name="defaultPictureType">Default picture type</param> /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param> /// <returns>Picture URL</returns> public virtual string GetDefaultPictureUrl(int targetSize = 0, PictureType defaultPictureType = PictureType.Entity, string storeLocation = null) { string defaultImageFileName; switch (defaultPictureType) { case PictureType.Avatar: defaultImageFileName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", NopMediaDefaults.DefaultAvatarFileName); break; case PictureType.Entity: default: defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", NopMediaDefaults.DefaultImageFileName); break; } var filePath = GetPictureLocalPath(defaultImageFileName); if (!_fileProvider.FileExists(filePath)) { return(string.Empty); } if (targetSize == 0) { var url = GetImagesPathUrl(storeLocation) + defaultImageFileName; return(url); } else { var fileExtension = _fileProvider.GetFileExtension(filePath); var thumbFileName = $"{_fileProvider.GetFileNameWithoutExtension(filePath)}_{targetSize}{fileExtension}"; var thumbFilePath = GetThumbLocalPath(thumbFileName); if (!GeneratedThumbExists(thumbFilePath, thumbFileName)) { using (var image = Image.Load(filePath, out var imageFormat)) { image.Mutate(imageProcess => imageProcess.Resize(new ResizeOptions { Mode = ResizeMode.Max, Size = CalculateDimensions(image.Size(), targetSize) })); var pictureBinary = EncodeImage(image, imageFormat); SaveThumb(thumbFilePath, thumbFileName, imageFormat.DefaultMimeType, pictureBinary); } } var url = GetThumbUrl(thumbFileName, storeLocation); return(url); } }
public virtual IActionResult AsyncUpload() { var httpPostedFile = Request.Form.Files.FirstOrDefault(); if (httpPostedFile == null) { return(Json(new { success = false, message = "No file uploaded", downloadGuid = Guid.Empty })); } var fileBinary = _downloadService.GetDownloadBits(httpPostedFile); var qqFileNameParameter = "qqfilename"; var fileName = httpPostedFile.FileName; if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter)) { fileName = Request.Form[qqFileNameParameter].ToString(); } //remove path (passed in IE) fileName = _fileProvider.GetFileName(fileName); var contentType = httpPostedFile.ContentType; var fileExtension = _fileProvider.GetFileExtension(fileName); if (!string.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } var download = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = string.Empty, DownloadBinary = fileBinary, ContentType = contentType, //we store filename without extension for downloads Filename = _fileProvider.GetFileNameWithoutExtension(fileName), Extension = fileExtension, IsNew = true }; _downloadService.InsertDownload(download); //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return(Json(new { success = true, downloadId = download.Id, downloadUrl = Url.Action("DownloadFile", new { downloadGuid = download.DownloadGuid }) })); }
public virtual IActionResult Upload() { if (!_permissionService.Authorize(StandardPermissionProvider.HtmlEditorManagePictures)) { ViewData[RESULTCODE_FIELD_KEY] = "failed"; ViewData[RESULT_FIELD_KEY] = "No access to this functionality"; return(View()); } if (Request.Form.Files.Count == 0) { throw new Exception("No file uploaded"); } var uploadFile = Request.Form.Files.FirstOrDefault(); if (uploadFile == null) { ViewData[RESULTCODE_FIELD_KEY] = "failed"; ViewData[RESULT_FIELD_KEY] = "No file name provided"; return(View()); } var fileName = _fileProvider.GetFileName(uploadFile.FileName); if (string.IsNullOrEmpty(fileName)) { ViewData[RESULTCODE_FIELD_KEY] = "failed"; ViewData[RESULT_FIELD_KEY] = "No file name provided"; return(View()); } var directory = "~/wwwroot/images/uploaded/"; var filePath = _fileProvider.Combine(_fileProvider.MapPath(directory), fileName); var fileExtension = _fileProvider.GetFileExtension(filePath); if (!GetAllowedFileTypes().Contains(fileExtension)) { ViewData[RESULTCODE_FIELD_KEY] = "failed"; ViewData[RESULT_FIELD_KEY] = $"Files with {fileExtension} extension cannot be uploaded"; return(View()); } //A warning (SCS0018 - Path Traversal) from the "Security Code Scan" analyzer may appear at this point. //In this case, it is not relevant. The input is not supplied by user. using (var fileStream = new FileStream(filePath, FileMode.Create)) { uploadFile.CopyTo(fileStream); } ViewData[RESULTCODE_FIELD_KEY] = "success"; ViewData[RESULT_FIELD_KEY] = "success"; ViewData[FILENAME_FIELD_KEY] = Url.Content($"{directory}{fileName}"); return(View()); }
private void LogPictureInsertError(string picturePath, Exception ex) { var extension = _fileProvider.GetFileExtension(picturePath); var name = _fileProvider.GetFileNameWithoutExtension(picturePath); var point = string.IsNullOrEmpty(extension) ? string.Empty : "."; var fileName = _fileProvider.FileExists(picturePath) ? $"{name}{point}{extension}" : string.Empty; _logger.Error($"Insert picture failed (file name: {fileName})", ex); }
public virtual IActionResult Upload() { if (!_permissionService.Authorize(StandardPermissionProvider.HtmlEditorManagePictures)) { ViewData["resultCode"] = "failed"; ViewData["result"] = "No access to this functionality"; return(View()); } if (Request.Form.Files.Count == 0) { throw new Exception("No file uploaded"); } var uploadFile = Request.Form.Files.FirstOrDefault(); if (uploadFile == null) { ViewData["resultCode"] = "failed"; ViewData["result"] = "No file name provided"; return(View()); } var fileName = _fileProvider.GetFileName(uploadFile.FileName); if (string.IsNullOrEmpty(fileName)) { ViewData["resultCode"] = "failed"; ViewData["result"] = "No file name provided"; return(View()); } var directory = "~/wwwroot/images/uploaded/"; var filePath = _fileProvider.Combine(_fileProvider.MapPath(directory), fileName); var fileExtension = _fileProvider.GetFileExtension(filePath); if (!GetAllowedFileTypes().Contains(fileExtension)) { ViewData["resultCode"] = "failed"; ViewData["result"] = $"Files with {fileExtension} extension cannot be uploaded"; return(View()); } using (var fileStream = new FileStream(filePath, FileMode.Create)) { uploadFile.CopyTo(fileStream); } ViewData["resultCode"] = "success"; ViewData["result"] = "success"; ViewData["filename"] = Url.Content($"{directory}{fileName}"); return(View()); }
public virtual IActionResult UploadFileReturnRequest() { if (!_orderSettings.ReturnRequestsEnabled || !_orderSettings.ReturnRequestsAllowFiles) { return(Json(new { success = false, downloadGuid = Guid.Empty, })); } var httpPostedFile = Request.Form.Files.FirstOrDefault(); if (httpPostedFile == null) { return(Json(new { success = false, message = "No file uploaded", downloadGuid = Guid.Empty, })); } var fileBinary = httpPostedFile.GetDownloadBits(); var qqFileNameParameter = "qqfilename"; var fileName = httpPostedFile.FileName; if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter)) { fileName = Request.Form[qqFileNameParameter].ToString(); } //remove path (passed in IE) fileName = _fileProvider.GetFileName(fileName); var contentType = httpPostedFile.ContentType; var fileExtension = _fileProvider.GetFileExtension(fileName); if (!string.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } var validationFileMaximumSize = _orderSettings.ReturnRequestsFileMaximumSize; if (validationFileMaximumSize > 0) { //compare in bytes var maxFileSizeBytes = validationFileMaximumSize * 1024; if (fileBinary.Length > maxFileSizeBytes) { return(Json(new { success = false, message = string.Format(_localizationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), validationFileMaximumSize), downloadGuid = Guid.Empty, })); } } var download = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = "", DownloadBinary = fileBinary, ContentType = contentType, //we store filename without extension for downloads Filename = _fileProvider.GetFileNameWithoutExtension(fileName), Extension = fileExtension, IsNew = true }; _downloadService.InsertDownload(download); //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return(Json(new { success = true, message = _localizationService.GetResource("ShoppingCart.FileUploaded"), downloadUrl = Url.Action("GetFileUpload", "Download", new { downloadId = download.DownloadGuid }), downloadGuid = download.DownloadGuid, })); }
public virtual IActionResult AsyncUpload() { //if (!_permissionService.Authorize(StandardPermissionProvider.UploadPictures)) // return Json(new { success = false, error = "You do not have required permissions" }, "text/plain"); var httpPostedFile = Request.Form.Files.FirstOrDefault(); if (httpPostedFile == null) { return(Json(new { success = false, message = "No file uploaded" })); } var fileBinary = _downloadService.GetDownloadBits(httpPostedFile); const string qqFileNameParameter = "qqfilename"; var fileName = httpPostedFile.FileName; if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter)) { fileName = Request.Form[qqFileNameParameter].ToString(); } //remove path (passed in IE) fileName = _fileProvider.GetFileName(fileName); var contentType = httpPostedFile.ContentType; var fileExtension = _fileProvider.GetFileExtension(fileName); if (!string.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } //contentType is not always available //that's why we manually update it here //http://www.sfsu.edu/training/mimetype.htm if (string.IsNullOrEmpty(contentType)) { switch (fileExtension) { case ".bmp": contentType = MimeTypes.ImageBmp; break; case ".gif": contentType = MimeTypes.ImageGif; break; case ".jpeg": case ".jpg": case ".jpe": case ".jfif": case ".pjpeg": case ".pjp": contentType = MimeTypes.ImageJpeg; break; case ".png": contentType = MimeTypes.ImagePng; break; case ".tiff": case ".tif": contentType = MimeTypes.ImageTiff; break; default: break; } } try { var picture = _pictureService.InsertPicture(fileBinary, contentType, null); //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return(Json(new { success = true, pictureId = picture.Id, imageUrl = _pictureService.GetPictureUrl(picture, 100) })); } catch (Exception exc) { _logger.Error(exc.Message, exc, _workContext.CurrentCustomer); return(Json(new { success = false, message = "Picture cannot be saved" })); } }
public virtual object UploadImage(IFormFile file) { if (file == null) { throw new AbpException("No file uploaded"); } var fileBinary = downloadService.GetDownloadBits(file); const string qqFileNameParameter = "qqfilename"; var fileName = file.FileName; if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter)) { fileName = Request.Form[qqFileNameParameter].ToString(); } //remove path (passed in IE) fileName = fileProvider.GetFileName(fileName); var contentType = file.ContentType; var fileExtension = fileProvider.GetFileExtension(fileName); if (!string.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } if (string.IsNullOrEmpty(contentType)) { switch (fileExtension) { case ".bmp": contentType = MimeTypes.ImageBmp; break; case ".gif": contentType = MimeTypes.ImageGif; break; case ".jpeg": case ".jpg": case ".jpe": case ".jfif": case ".pjpeg": case ".pjp": contentType = MimeTypes.ImageJpeg; break; case ".png": contentType = MimeTypes.ImagePng; break; case ".tiff": case ".tif": contentType = MimeTypes.ImageTiff; break; default: break; } } var picture = pictureAppService.InsertPicture(fileBinary, contentType, null); return(new { Id = picture.Id, Path = pictureAppService.GetPictureUrl(picture.Id, 200) }); }
/// <summary> /// Gets the default picture URL /// </summary> /// <param name="targetSize">The target picture size (longest side)</param> /// <param name="defaultPictureType">Default picture type</param> /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param> /// <returns>Picture URL</returns> public virtual string GetDefaultPictureUrl(int targetSize = 0, PictureType defaultPictureType = PictureType.Entity, string storeLocation = null) { string defaultImageFileName; switch (defaultPictureType) { case PictureType.Avatar: defaultImageFileName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", "default-avatar.jpg"); break; case PictureType.Entity: default: defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image.png"); break; } var filePath = GetPictureLocalPath(defaultImageFileName); if (!_fileProvider.FileExists(filePath)) { return(""); } if (targetSize == 0) { var url = (!string.IsNullOrEmpty(storeLocation) ? storeLocation : _webHelper.GetStoreLocation()) + "images/" + defaultImageFileName; return(url); } else { var fileExtension = _fileProvider.GetFileExtension(filePath); var thumbFileName = $"{_fileProvider.GetFileNameWithoutExtension(filePath)}_{targetSize}{fileExtension}"; var thumbFilePath = GetThumbLocalPath(thumbFileName); if (!GeneratedThumbExists(thumbFilePath, thumbFileName)) { using (var b = new Bitmap(filePath)) { using (var destStream = new MemoryStream()) { var newSize = CalculateDimensions(b.Size, targetSize); ImageBuilder.Current.Build(b, destStream, new ResizeSettings { Width = newSize.Width, Height = newSize.Height, Scale = ScaleMode.Both, Quality = _mediaSettings.DefaultImageQuality }); var destBinary = destStream.ToArray(); SaveThumb(thumbFilePath, thumbFileName, "", destBinary); } } } var url = GetThumbUrl(thumbFileName, storeLocation); return(url); } }
public IActionResult UploadFileProductAttribute(int attributeId) { var attribute = _productAttributeService.GetProductAttributeMappingById(attributeId); if (attribute == null || attribute.AttributeControlType != AttributeControlType.FileUpload) { return(Json(new { success = false, downloadGuid = Guid.Empty })); } var httpPostedFile = Request.Form.Files.FirstOrDefault(); if (httpPostedFile == null) { return(Json(new { success = false, message = "No file uploaded", downloadGuid = Guid.Empty })); } var fileBinary = _downloadService.GetDownloadBits(httpPostedFile); var qqFileNameParameter = "qqfilename"; var fileName = httpPostedFile.FileName; if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter)) { fileName = Request.Form[qqFileNameParameter].ToString(); } //remove path (passed in IE) fileName = _fileProvider.GetFileName(fileName); var contentType = httpPostedFile.ContentType; var fileExtension = _fileProvider.GetFileExtension(fileName); if (!string.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } if (attribute.ValidationFileMaximumSize.HasValue) { //compare in bytes var maxFileSizeBytes = attribute.ValidationFileMaximumSize.Value * 1024; if (fileBinary.Length > maxFileSizeBytes) { //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return(Json(new { success = false, message = string.Format(_localizationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), attribute.ValidationFileMaximumSize.Value), downloadGuid = Guid.Empty })); } } var download = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = "", DownloadBinary = fileBinary, ContentType = contentType, //we store filename without extension for downloads Filename = _fileProvider.GetFileNameWithoutExtension(fileName), Extension = fileExtension, IsNew = true }; _downloadService.InsertDownload(download); //generate new image merging the uploaded custom logo and product picture //newly added features for the override var logoPosition = _logoPositionService.GetByProductId(attribute.ProductId); (int, string)imagePath = _customLogoService.MergeProductPictureWithLogo( download.DownloadBinary, download.Id, attribute.ProductId, ProductPictureModifierUploadType.Custom, logoPosition.Size, logoPosition.Opacity, logoPosition.XCoordinate, logoPosition.YCoordinate, _mediaSettings.ProductDetailsPictureSize ); //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return(Json(new { success = true, message = _localizationService.GetResource("ShoppingCart.FileUploaded"), downloadUrl = Url.Action("GetFileUpload", "Download", new { downloadId = download.DownloadGuid }), downloadGuid = download.DownloadGuid, imagePath = imagePath.Item2, //added property for the override })); }