/// <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("]"); }
private WorkFile UploadFile(IFormFile httpPostedFile) { if (httpPostedFile == null) { return(null); } var fileBinary = _workfileService.GetWorkFileBits(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 fwork = new WorkFile { FileGuid = Guid.NewGuid(), FileContent = null, MimeType = contentType, //we store filename without extension for downloads FileName = _fileProvider.GetFileNameWithoutExtension(fileName), Extension = fileExtension, CreatedDate = DateTime.Now, CreatorId = _workContext.CurrentCustomer.Id, ContentLength = Convert.ToInt32(fileBinary.LongLength / 1024) //luu thanh kb }; _workfileService.InsertWorkFile(fwork); //luu file content ra ngoai SaveWorkFileOnDisk(fwork, fileBinary); //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return(fwork); }
/// <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 }) })); }
/// <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))); }
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); }
public virtual IActionResult MaintenanceDeleteFiles(MaintenanceModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenance)) { return(AccessDeniedView()); } var startDateValue = model.DeleteExportedFiles.StartDate == null ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.DeleteExportedFiles.StartDate.Value, _dateTimeHelper.CurrentTimeZone); var endDateValue = model.DeleteExportedFiles.EndDate == null ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.DeleteExportedFiles.EndDate.Value, _dateTimeHelper.CurrentTimeZone).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(_fileProvider.Combine(EXPORT_IMPORT_PATH, fileName)); 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) { ErrorNotification(exc, false); } } return(View(model)); }
/// <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 GSException("All installation resources must have an attribute Name=\"Value\"."); } var resourceName = resNameAttribute.Value.Trim(); if (string.IsNullOrEmpty(resourceName)) { throw new GSException("All installation resource attributes 'Name' must have a value.'"); } if (resValueNode == null) { throw new GSException("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); }
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", downloadGuid = Guid.Empty })); } 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; } } 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) })); }
static PluginManager() { //we use the default file provider, since the DI isn't initialized yet _fileProvider = CommonHelper.DefaultFileProvider; //get all libraries from /bin/{version}/ directory _baseAppLibraries = _fileProvider.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Select(fi => _fileProvider.GetFileName(fi)).ToList(); //get all libraries from base site directory if (!AppDomain.CurrentDomain.BaseDirectory.Equals(Environment.CurrentDirectory, StringComparison.InvariantCultureIgnoreCase)) { _baseAppLibraries.AddRange(_fileProvider.GetFiles(Environment.CurrentDirectory, "*.dll").Select(fi => _fileProvider.GetFileName(fi))); } //get all libraries from refs directory var refsPathName = _fileProvider.Combine(Environment.CurrentDirectory, GSPluginDefaults.RefsPathName); if (_fileProvider.DirectoryExists(refsPathName)) { _baseAppLibraries.AddRange(_fileProvider.GetFiles(refsPathName, "*.dll").Select(fi => _fileProvider.GetFileName(fi))); } }