/// <summary> /// Prepare paged backup file list model /// </summary> /// <param name="searchModel">Backup file search model</param> /// <returns>Backup file list model</returns> public virtual Task <BackupFileListModel> PrepareBackupFileListModelAsync(BackupFileSearchModel searchModel) { if (searchModel == null) { throw new ArgumentNullException(nameof(searchModel)); } //get backup files var backupFiles = _maintenanceService.GetAllBackupFiles().ToPagedList(searchModel); //prepare list model var model = new BackupFileListModel().PrepareToGrid(searchModel, backupFiles, () => { return(backupFiles.Select(file => new BackupFileModel { Name = _fileProvider.GetFileName(file), //fill in additional values (not existing in the entity) Length = $"{_fileProvider.FileLength(file) / 1024f / 1024f:F2} Mb", Link = $"{(_webHelper.GetStoreLocation(false))}db_backups/{_fileProvider.GetFileName(file)}" })); }); return(Task.FromResult(model)); }
static ApplicationPartManagerExtensions() { //we use the default file provider, since the DI isn't initialized yet _fileProvider = CommonHelper.DefaultFileProvider; _baseAppLibraries = new List <string>(); //get all libraries from /bin/{version}/ directory _baseAppLibraries.AddRange(_fileProvider.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll") .Select(fileName => _fileProvider.GetFileName(fileName))); //get all libraries from base site directory if (!AppDomain.CurrentDomain.BaseDirectory.Equals(Environment.CurrentDirectory, StringComparison.InvariantCultureIgnoreCase)) { _baseAppLibraries.AddRange(_fileProvider.GetFiles(Environment.CurrentDirectory, "*.dll") .Select(fileName => _fileProvider.GetFileName(fileName))); } //get all libraries from refs directory var refsPathName = _fileProvider.Combine(Environment.CurrentDirectory, NopPluginDefaults.RefsPathName); if (_fileProvider.DirectoryExists(refsPathName)) { _baseAppLibraries.AddRange(_fileProvider.GetFiles(refsPathName, "*.dll") .Select(fileName => _fileProvider.GetFileName(fileName))); } }
/// <summary> /// Get files in the passed directory /// </summary> /// <param name="directoryPath">Path to the files directory</param> /// <param name="type">Type of the files</param> /// <returns>A task that represents the completion of the operation</returns> protected virtual async Task GetFilesAsync(string directoryPath, string type) { directoryPath = GetVirtualPath(directoryPath); var files = GetFiles(GetFullPath(directoryPath), type); await HttpContext.Response.WriteAsync("["); for (var i = 0; i < files.Count; i++) { var width = 0; var height = 0; var physicalPath = files[i]; if (GetFileType(_fileProvider.GetFileExtension(files[i])) == "image") { using (var stream = new FileStream(physicalPath, FileMode.Open)) { using (var image = Image.FromStream(stream)) { width = image.Width; height = image.Height; } } } await HttpContext.Response.WriteAsync($"{{\"p\":\"{directoryPath.TrimEnd('/')}/{_fileProvider.GetFileName(physicalPath)}\",\"t\":\"{Math.Ceiling(GetTimestamp(_fileProvider.GetLastWriteTime(physicalPath)))}\",\"s\":\"{_fileProvider.FileLength(physicalPath)}\",\"w\":\"{width}\",\"h\":\"{height}\"}}"); if (i < files.Count - 1) { await HttpContext.Response.WriteAsync(","); } } await HttpContext.Response.WriteAsync("]"); }
public async Task <IActionResult> DownloadLabel(ShipmentDetailsModel model) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageOrders)) { return(AccessDeniedView()); } var shipment = await _shipmentService.GetShipmentByIdAsync(model.Id); if (shipment is not null) { var((downloadUrl, contentType), error) = await _easyPostService.DownloadLabelAsync(shipment, model.LabelFormat); if (!string.IsNullOrEmpty(error)) { var locale = await _localizationService.GetResourceAsync("Plugins.Shipping.EasyPost.Error"); _notificationService.ErrorNotification(string.Format(locale, error, Url.Action("List", "Log")), false); } else { //return file var filename = _nopFileProvider.GetFileName(downloadUrl); var client = _httpClientFactory.CreateClient(NopHttpDefaults.DefaultHttpClient); var stream = await client.GetStreamAsync(downloadUrl); return(File(stream, contentType, filename, true)); } } return(RedirectToAction("ShipmentDetails", "Order", new { id = shipment?.Id ?? 0 })); }
/// <summary> /// Copy the plugin file to shadow copy directory /// </summary> /// <param name="pluginFilePath">Plugin file path</param> /// <param name="shadowCopyPlugFolder">Path to shadow copy folder</param> /// <returns>File path to shadow copy of plugin file</returns> protected static string ShadowCopyFile(string pluginFilePath, string shadowCopyPlugFolder) { var shouldCopy = true; var shadowCopiedPlug = _fileProvider.Combine(shadowCopyPlugFolder, _fileProvider.GetFileName(pluginFilePath)); //check if a shadow copied file already exists and if it does, check if it's updated, if not don't copy if (_fileProvider.FileExists(shadowCopiedPlug)) { //it's better to use LastWriteTimeUTC, but not all file systems have this property //maybe it is better to compare file hash? var areFilesIdentical = _fileProvider.GetCreationTime(shadowCopiedPlug).ToUniversalTime().Ticks >= _fileProvider.GetCreationTime(pluginFilePath).ToUniversalTime().Ticks; if (areFilesIdentical) { Debug.WriteLine("Not copying; files appear identical: '{0}'", _fileProvider.GetFileName(shadowCopiedPlug)); shouldCopy = false; } else { //delete an existing file //More info: https://www.nopcommerce.com/boards/t/11511/access-error-nopplugindiscountrulesbillingcountrydll.aspx?p=4#60838 Debug.WriteLine("New plugin found; Deleting the old file: '{0}'", _fileProvider.GetFileName(shadowCopiedPlug)); _fileProvider.DeleteFile(shadowCopiedPlug); } } if (!shouldCopy) { return(shadowCopiedPlug); } try { _fileProvider.FileCopy(pluginFilePath, shadowCopiedPlug, true); } catch (IOException) { Debug.WriteLine(shadowCopiedPlug + " is locked, attempting to rename"); //this occurs when the files are locked, //for some reason devenv locks plugin files some times and for another crazy reason you are allowed to rename them //which releases the lock, so that it what we are doing here, once it's renamed, we can re-shadow copy try { var oldFile = shadowCopiedPlug + Guid.NewGuid().ToString("N") + ".old"; _fileProvider.FileMove(shadowCopiedPlug, oldFile); } catch (IOException exc) { throw new IOException(shadowCopiedPlug + " rename failed, cannot initialize plugin", exc); } //OK, we've made it this far, now retry the shadow copy _fileProvider.FileCopy(pluginFilePath, shadowCopiedPlug, true); } return(shadowCopiedPlug); }
/// <summary> /// Get a picture local path /// </summary> /// <param name="picture">Picture instance</param> /// <param name="targetSize">The target picture size (longest side)</param> /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param> /// <returns></returns> public virtual string GetThumbLocalPath(Picture picture, int targetSize = 0, bool showDefaultPicture = true) { var url = GetPictureUrl(picture, targetSize, showDefaultPicture); if (string.IsNullOrEmpty(url)) { return(string.Empty); } return(GetThumbLocalPath(_fileProvider.GetFileName(url))); }
/// <summary> /// Get a list of available languages /// </summary> /// <returns>Available installation languages</returns> public virtual IList <InstallationLanguage> GetAvailableLanguages() { if (_availableLanguages != null) { return(_availableLanguages); } _availableLanguages = new List <InstallationLanguage>(); foreach (var filePath in _fileProvider.EnumerateFiles(_fileProvider.MapPath("~/App_Data/Localization/Installation/"), "*.xml")) { var xmlDocument = new XmlDocument(); xmlDocument.Load(filePath); //get language code var languageCode = ""; //we file name format: installation.{languagecode}.xml var r = new Regex(Regex.Escape("installation.") + "(.*?)" + Regex.Escape(".xml")); var matches = r.Matches(_fileProvider.GetFileName(filePath)); foreach (Match match in matches) { languageCode = match.Groups[1].Value; } //at now we use language codes only (not full culture names) languageCode = languageCode[..2];
/// <summary> /// Prepare paged backup file list model /// </summary> /// <param name="searchModel">Backup file search model</param> /// <returns>Backup file list model</returns> public virtual BackupFileListModel PrepareBackupFileListModel(BackupFileSearchModel searchModel) { if (searchModel == null) { throw new ArgumentNullException(nameof(searchModel)); } //get backup files var backupFiles = _maintenanceService.GetAllBackupFiles().ToList(); //prepare list model var model = new BackupFileListModel { Data = backupFiles.PaginationByRequestModel(searchModel).Select(file => { //fill in model values from the entity var backupFileModel = new BackupFileModel { Name = _fileProvider.GetFileName(file) }; //fill in additional values (not existing in the entity) backupFileModel.Length = $"{_fileProvider.FileLength(file) / 1024f / 1024f:F2} Mb"; backupFileModel.Link = $"{_webHelper.GetStoreLocation(false)}db_backups/{backupFileModel.Name}"; return(backupFileModel); }), Total = backupFiles.Count }; return(model); }
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 }) })); }
private string DownloadFile(string urlString, IList <string> downloadedFiles) { if (string.IsNullOrEmpty(urlString)) { return(string.Empty); } if (!Uri.IsWellFormedUriString(urlString, UriKind.Absolute)) { return(urlString); } //ensure that temp directory is created var tempDirectory = _fileProvider.MapPath(UPLOADS_TEMP_PATH); _fileProvider.CreateDirectory(tempDirectory); var fileName = _fileProvider.GetFileName(urlString); if (string.IsNullOrEmpty(fileName)) { return(string.Empty); } var filePath = _fileProvider.Combine(tempDirectory, fileName); try { WebRequest.Create(urlString); } catch { return(string.Empty); } try { byte[] fileData; using (var client = new WebClient()) { fileData = client.DownloadData(urlString); } using (var fs = new FileStream(filePath, FileMode.OpenOrCreate)) { fs.Write(fileData, 0, fileData.Length); } downloadedFiles?.Add(filePath); return(filePath); } catch (Exception ex) { _logger.Error("Download image failed", ex); } return(string.Empty); }
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()); }
public virtual async Task <IActionResult> MaintenanceDeleteFiles(MaintenanceModel model) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageMaintenance)) { return(AccessDeniedView()); } var startDateValue = model.DeleteExportedFiles.StartDate == null ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.DeleteExportedFiles.StartDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()); var endDateValue = model.DeleteExportedFiles.EndDate == null ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.DeleteExportedFiles.EndDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1); model.DeleteExportedFiles.NumberOfDeletedFiles = 0; foreach (var fullPath in _fileProvider.GetFiles(_fileProvider.GetAbsolutePath(EXPORT_IMPORT_PATH))) { try { var fileName = _fileProvider.GetFileName(fullPath); if (fileName.Equals("index.htm", StringComparison.InvariantCultureIgnoreCase)) { continue; } var info = _fileProvider.GetFileInfo(fullPath); var lastModifiedTimeUtc = info.LastModified.UtcDateTime; if ((!startDateValue.HasValue || startDateValue.Value < lastModifiedTimeUtc) && (!endDateValue.HasValue || lastModifiedTimeUtc < endDateValue.Value)) { _fileProvider.DeleteFile(fullPath); model.DeleteExportedFiles.NumberOfDeletedFiles++; } } catch (Exception exc) { await _notificationService.ErrorNotificationAsync(exc); } } return(View(model)); }
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()); }
/// <summary> /// Indicates whether assembly file is already loaded /// </summary> /// <param name="filePath">File path</param> /// <returns>True if assembly file is already loaded; otherwise false</returns> private static bool IsAlreadyLoaded(string filePath) { //search library file name in base directory to ignore already existing (loaded) libraries //(we do it because not all libraries are loaded immediately after application start) if (_baseAppLibraries.Any(sli => sli.Equals(_fileProvider.GetFileName(filePath), StringComparison.InvariantCultureIgnoreCase))) { return(true); } //compare full assembly name //var fileAssemblyName = AssemblyName.GetAssemblyName(filePath); //foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) //{ // if (a.FullName.Equals(fileAssemblyName.FullName, StringComparison.InvariantCultureIgnoreCase)) // return true; //} //return false; //do not compare the full assembly name, just filename try { var fileNameWithoutExt = _fileProvider.GetFileNameWithoutExtension(filePath); if (string.IsNullOrEmpty(fileNameWithoutExt)) { throw new Exception($"Cannot get file extension for {_fileProvider.GetFileName(filePath)}"); } foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) { var assemblyName = a.FullName.Split(',').FirstOrDefault(); if (fileNameWithoutExt.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase)) { return(true); } } } catch (Exception exc) { Debug.WriteLine("Cannot validate whether an assembly is already loaded. " + exc); } return(false); }
/// <summary> /// Get a list of available languages /// </summary> /// <returns>Available installation languages</returns> public virtual IList <InstallationLanguage> GetAvailableLanguages() { if (_availableLanguages != null) { return(_availableLanguages); } _availableLanguages = new List <InstallationLanguage>(); foreach (var filePath in _fileProvider.EnumerateFiles(_fileProvider.MapPath("~/App_Data/Localization/Installation/"), "*.xml")) { var xmlDocument = new XmlDocument(); xmlDocument.Load(filePath); //get language code var languageCode = ""; //we file name format: installation.{languagecode}.xml var r = new Regex(Regex.Escape("installation.") + "(.*?)" + Regex.Escape(".xml")); var matches = r.Matches(_fileProvider.GetFileName(filePath)); foreach (Match match in matches) { languageCode = match.Groups[1].Value; } var languageNode = xmlDocument.SelectSingleNode(@"//Language"); if (languageNode == null || languageNode.Attributes == null) { continue; } //get language friendly name var languageName = languageNode.Attributes["Name"].InnerText.Trim(); //is default var isDefaultAttribute = languageNode.Attributes["IsDefault"]; var isDefault = isDefaultAttribute != null && Convert.ToBoolean(isDefaultAttribute.InnerText.Trim()); //is default var isRightToLeftAttribute = languageNode.Attributes["IsRightToLeft"]; var isRightToLeft = isRightToLeftAttribute != null && Convert.ToBoolean(isRightToLeftAttribute.InnerText.Trim()); //create language var language = new InstallationLanguage { Code = languageCode, Name = languageName, IsDefault = isDefault, IsRightToLeft = isRightToLeft, }; //load resources var resources = xmlDocument.SelectNodes(@"//Language/LocaleResource"); if (resources == null) { continue; } foreach (XmlNode resNode in resources) { if (resNode.Attributes == null) { continue; } var resNameAttribute = resNode.Attributes["Name"]; var resValueNode = resNode.SelectSingleNode("Value"); if (resNameAttribute == null) { throw new NopException("All installation resources must have an attribute Name=\"Value\"."); } var resourceName = resNameAttribute.Value.Trim(); if (string.IsNullOrEmpty(resourceName)) { throw new NopException("All installation resource attributes 'Name' must have a value.'"); } if (resValueNode == null) { throw new NopException("All installation resources must have an element \"Value\"."); } var resourceValue = resValueNode.InnerText.Trim(); language.Resources.Add(new InstallationLocaleResource { Name = resourceName, Value = resourceValue }); } _availableLanguages.Add(language); _availableLanguages = _availableLanguages.OrderBy(l => l.Name).ToList(); } return(_availableLanguages); }
/// <summary> /// Upload multiple items from the archive into the physical directory /// </summary> /// <param name="archivePath">Path to the archive</param> /// <param name="uploadedItems">Uploaded items</param> /// <returns>List of uploaded items descriptor</returns> protected virtual IList <IDescriptor> UploadMultipleItems(string archivePath, IList <UploadedItem> uploadedItems) { //get path to the plugins directory var pluginsDirectory = _fileProvider.MapPath(NopPluginDefaults.Path); //get path to the themes directory var themesDirectory = string.Empty; if (!string.IsNullOrEmpty(NopPluginDefaults.ThemesPath)) { themesDirectory = _fileProvider.MapPath(NopPluginDefaults.ThemesPath); } //get descriptors of items contained in the archive var descriptors = new List <IDescriptor>(); using (var archive = ZipFile.OpenRead(archivePath)) { foreach (var item in uploadedItems) { if (!item.Type.HasValue) { continue; } //ensure that the current version of nopCommerce is supported if (!item.SupportedVersions?.Contains(NopVersion.CURRENT_VERSION) ?? true) { continue; } //the item path should end with a slash var itemPath = $"{item.DirectoryPath?.TrimEnd('/')}/"; //get path to the descriptor entry in the archive var descriptorPath = string.Empty; if (item.Type == UploadedItemType.Plugin) { descriptorPath = $"{itemPath}{NopPluginDefaults.DescriptionFileName}"; } if (item.Type == UploadedItemType.Theme && !string.IsNullOrEmpty(NopPluginDefaults.ThemeDescriptionFileName)) { descriptorPath = $"{itemPath}{NopPluginDefaults.ThemeDescriptionFileName}"; } //try to get the descriptor entry var descriptorEntry = archive.Entries.FirstOrDefault(entry => entry.FullName.Equals(descriptorPath, StringComparison.InvariantCultureIgnoreCase)); if (descriptorEntry == null) { continue; } //try to get descriptor of the uploaded item IDescriptor descriptor = null; using (var unzippedEntryStream = descriptorEntry.Open()) { using var reader = new StreamReader(unzippedEntryStream); //whether a plugin is upload if (item.Type == UploadedItemType.Plugin) { descriptor = PluginDescriptor.GetPluginDescriptorFromText(reader.ReadToEnd()); } //or whether a theme is upload if (item.Type == UploadedItemType.Theme) { descriptor = _themeProvider.GetThemeDescriptorFromText(reader.ReadToEnd()); } } if (descriptor == null) { continue; } //ensure that the plugin current version is supported if (descriptor is PluginDescriptor pluginDescriptor && !pluginDescriptor.SupportedVersions.Contains(NopVersion.CURRENT_VERSION)) { continue; } //get path to upload var uploadedItemDirectoryName = _fileProvider.GetFileName(itemPath.TrimEnd('/')); var pathToUpload = _fileProvider.Combine(item.Type == UploadedItemType.Plugin ? pluginsDirectory : themesDirectory, uploadedItemDirectoryName); //ensure it's a new directory (e.g. some old files are not required when re-uploading a plugin or a theme) //furthermore, zip extract functionality cannot override existing files //but there could deletion issues (related to file locking, etc). In such cases the directory should be deleted manually if (_fileProvider.DirectoryExists(pathToUpload)) { _fileProvider.DeleteDirectory(pathToUpload); } //unzip entries into files var entries = archive.Entries.Where(entry => entry.FullName.StartsWith(itemPath, StringComparison.InvariantCultureIgnoreCase)); foreach (var entry in entries) { //get name of the file var fileName = entry.FullName[itemPath.Length..];
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 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 })); }
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) }); }