/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); Page.ClientScript.RegisterClientScriptInclude(GetType(), "FU_Script", ScriptPath + "fileupload.js"); Page.ClientScript.RegisterClientScriptInclude(GetType(), "FU_Script1", ScriptPath + "prototype.js"); Page.ClientScript.RegisterClientScriptInclude(GetType(), "FU_Script2", ScriptPath + "scriptaculous.js?load=effects"); Page.ClientScript.RegisterClientScriptInclude(GetType(), "FU_Script3", ScriptPath + "modalbox.js"); Page.ClientScript.RegisterStartupScript(GetType(), "FU_Init", "up_initFileUploads('" + ImagePath + "','" + (String.IsNullOrEmpty(AllowedFileExtensions) ? "" : AllowedFileExtensions.ToLower()) + "');", true); AddStyleLink("modalbox.css"); AddStyleLink("uploadstyles.css"); // Always add modalbox.css first as uploadstyles.css has overrides EnsureChildControls(); _uploadID.Value = UPLOAD_ID_TAG + Guid.NewGuid(); if (ShowProgressBar) { Page.ClientScript.RegisterOnSubmitStatement(GetType(), "FU_Submit", "up_BeginUpload('" + _uploadID.ClientID + "'," + (ShowCancelButton ? "true" : "false") + ");"); } }
// To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://aka.ms/RazorPagesCRUD. public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } using (var memoryStream = new MemoryStream()) { await InPersonGuest.Document.CopyToAsync(memoryStream); var guest = new InPersonGuest { Extension = AllowedFileExtensions.GetNormalizedExtension(InPersonGuest.Document), ContentType = InPersonGuest.Document.ContentType, Name = InPersonGuest.Name, Content = memoryStream.ToArray(), RsvpId = UserId }; Context.InPersonGuests.Add(guest); await Context.SaveChangesAsync(); } return(RedirectToPage("./Dashboard")); }
public async Task <IActionResult> AddPictures(GalleryPicturesViewModel model) { var noPicturesSelected = model.Pictures == null || !model.Pictures.Any(); if (noPicturesSelected) { ModelState.AddModelError(nameof(model.Pictures), "You have to select at least one picture."); } if (!noPicturesSelected && model.Pictures.ToList().Any(f => !AllowedFileExtensions.Contains(f.ContentType))) { ModelState.AddModelError(nameof(model.Pictures), "Only jpg and jpeg image files allowed."); } if (!noPicturesSelected && model.Pictures.ToList().Any(f => f.Length == 0 || f.Length > ImageFileMaxLength)) { ModelState.AddModelError(nameof(model.Pictures), $"Image cannot be bigger than {(ImageFileMaxLength / 1024) / 1000:D} MB."); } if (!ModelState.IsValid) { return(View(model)); } var skippedPictures = await StorePictures(model.Pictures, model.GalleryId); return(View(model)); }
/// <summary> /// 验证是否支持当前文件扩展名 /// </summary> /// <param name="fileName">文件名(带后缀)</param> /// <returns>true-支持,false-不支持</returns> public bool ValidateFileExtensions(string fileName) { string fileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1); string[] extensions = AllowedFileExtensions.Split(','); return(extensions.Where(n => n.Equals(fileExtension, StringComparison.InvariantCultureIgnoreCase)).Count() > 0); }
/// <summary> /// Determines if the found embedded file might be mapped and provided. /// </summary> /// <param name="resourceName"></param> /// <returns></returns> /// <remarks>Default implementation uses <see cref="AllowedFileExtensions"/> to determine which files to servce.</remarks> protected virtual bool IsFileAllowed(string resourceName) { if (resourceName == null) { throw new ArgumentNullException("resourceName"); } var extension = resourceName.Substring(resourceName.LastIndexOf('.') + 1); return(AllowedFileExtensions.Any(x => x == extension)); }
private void EnumerateDirectory(string path, bool addToHistory = true) { if (FileService != null) { if (addToHistory) { previousFolders.Push(CurrentFolder); } CurrentFolder = new FolderItem(path); var items = FileService.GetStorageItems(path); StorageItems.Clear(); StorageItems.AddRange(items.OfType <FolderItem>()); var files = items.OfType <FileItem>() .Where(x => AllowedFileExtensions.Count == 0 || AllowedFileExtensions.Contains(x.Extension)); StorageItems.AddRange(files); } }
/// <summary> /// Called when a document is getting closed /// </summary> /// <param name="document">The document that is getting closed</param> private void OnDocumentClosing(Document document) { if (document == null) { return; } Log.WriteLine(LogLevel.Debug, $"{nameof(OnDocumentClosing)}(Document: {document.Name})"); string extension = Path.GetExtension(document.FullName); if (!AllowedFileExtensions.Contains(extension)) { return; } _documentsToReformat.Remove(document); }
/// <summary> /// Called when a document is saved /// </summary> /// <param name="document">The document that is saved</param> private void OnDocumentSaved(Document document) { Log.WriteLine(LogLevel.Debug, $"{nameof(OnDocumentSaved)}(Document: {document.Name})"); if (IsReformatting || BuildingSolution > 0) { return; } string extension = Path.GetExtension(document.FullName); if (!AllowedFileExtensions.Contains(extension)) { return; } _documentsToReformat[document] = DateTime.Now; }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { if (Document != null) { if (Document.Length > 10485760) { yield return(new ValidationResult("File upload size limit is 10 MB.", new[] { nameof(Document) })); } string message = null; try { AllowedFileExtensions.ValidateFile(Document); } catch (Exception e) { message = e.Message; } if (message != null) { yield return(new ValidationResult(message, new[] { nameof(Document) })); } } }
/// <summary> Add the file input and the necessary script section, with /// all the options specfiedi here, directly to the streamwriter </summary> /// <param name="Output"> Writer to write to the stream </param> /// <param name="Extra_Indent"> Extra indent to begin each line with (purely for formatting) </param> /// <param name="Invalid_Message"> Message to display on fallback, particularly when HTML5 and flash both fail </param> public void Add_To_Stream(TextWriter Output, string Extra_Indent, String Invalid_Message) { if (Version == UploadiFive_Version_Enum.HTML5) { Output.WriteLine(Extra_Indent + " $('#" + FileInputID + "').uploadifive({"); } else { Output.WriteLine(Extra_Indent + " $('#" + FileInputID + "').uploadify({"); } // Add all the uploadifive options if (Auto.HasValue) { Output.WriteLine(Extra_Indent + " 'auto': " + Auto.Value.ToString().ToLower() + ","); } if (!string.IsNullOrEmpty(ButtonClass)) { Output.WriteLine(Extra_Indent + " 'buttonClass': '" + ButtonClass + "',"); } if (!string.IsNullOrEmpty(ButtonText)) { Output.WriteLine(Extra_Indent + " 'buttonText': '" + ButtonText + "',"); } if (!string.IsNullOrEmpty(CheckScript)) { Output.WriteLine(Extra_Indent + " 'checkScript': '" + CheckScript + "',"); } if (DragAndDrop.HasValue) { Output.WriteLine(Extra_Indent + " 'dnd': " + DragAndDrop.Value.ToString().ToLower() + ","); } if (!string.IsNullOrEmpty(FileObjName)) { Output.WriteLine(Extra_Indent + " 'fileObjName': '" + FileObjName + "',"); } if (!string.IsNullOrEmpty(FileSizeLimit)) { Output.WriteLine(Extra_Indent + " 'fileSizeLimit': '" + FileSizeLimit + "',"); } if (!string.IsNullOrEmpty(FileType)) { Output.WriteLine(Extra_Indent + " 'fileType': '" + FileType + "',"); } // Add the form data if (FormData.Count > 0) { Output.Write(Extra_Indent + " 'formData': { "); bool first = true; foreach (KeyValuePair <string, string> thisData in FormData) { // After the first one, start with the comma seperation if (first) { first = false; } else { Output.Write(", "); } Output.Write("'" + thisData.Key + "' : '" + thisData.Value + "'"); } Output.WriteLine(" },"); } // Finish the uploadifive options if (ButtonHeight.HasValue) { Output.WriteLine(Extra_Indent + " 'height': " + ButtonHeight.Value + ","); } if (!string.IsNullOrEmpty(ItemTemplate)) { Output.WriteLine(Extra_Indent + " 'itemTemplate': '" + ItemTemplate + "',"); } if (Method == UploadiFive_Method_Enum.Get) { Output.WriteLine(Extra_Indent + " 'method': 'get',"); } if (Multi.HasValue) { Output.WriteLine(Extra_Indent + " 'multi': " + Multi.Value.ToString().ToLower() + ","); } if (!string.IsNullOrEmpty(QueueID)) { Output.WriteLine(Extra_Indent + " 'queueID': '" + QueueID + "',"); } if (QueueSizeLimit.HasValue) { Output.WriteLine(Extra_Indent + " 'queueSizeLimit': " + QueueSizeLimit.Value + ","); } if (RemoveCompleted.HasValue) { Output.WriteLine(Extra_Indent + " 'removeCompleted': " + RemoveCompleted.Value.ToString().ToLower() + ","); } if (TruncateLength.HasValue) { Output.WriteLine(Extra_Indent + " 'truncateLength': " + TruncateLength.Value + ","); } if (UploadLimit.HasValue) { Output.WriteLine(Extra_Indent + " 'uploadLimit': " + UploadLimit.Value + ","); } if (ButtonWidth.HasValue) { Output.WriteLine(Extra_Indent + " 'width': " + ButtonWidth.Value + ","); } // Add some event handlers if (SubmitWhenQueueCompletes) { Output.WriteLine(Extra_Indent + " 'onQueueComplete': function (uploads) { $('#" + FileInputID + "').closest(\"form\").submit(); },"); } // Is there a file extension restriction here? if (!string.IsNullOrEmpty(AllowedFileExtensions)) { // Build the json array of possible file extensions string[] split = AllowedFileExtensions.Split(",|".ToCharArray()); StringBuilder jsonArrayBuilder = new StringBuilder(AllowedFileExtensions.Length * 2); bool first = true; foreach (string thisSplit in split) { if (first) { jsonArrayBuilder.Append("\"" + thisSplit.Trim().ToLower() + "\""); first = false; } else { jsonArrayBuilder.Append(", \"" + thisSplit.Trim().ToLower() + "\""); } } // Now, add the event if (Version == UploadiFive_Version_Enum.HTML5) { Output.WriteLine(Extra_Indent + " 'onAddQueueItem' : function(file) {"); } else { Output.WriteLine(Extra_Indent + " 'onSelect' : function(file) {"); } Output.WriteLine(Extra_Indent + " var extArray = JSON.parse('[ " + jsonArrayBuilder + " ]');"); Output.WriteLine(Extra_Indent + " var fileName = file.name;"); Output.WriteLine(Extra_Indent + " var ext = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();"); Output.WriteLine(Extra_Indent + " var isExtValid = false;"); Output.WriteLine(Extra_Indent + " for(var i = 0; i < extArray.length; i++) { "); Output.WriteLine(Extra_Indent + " if ( ext == extArray[i] ) { isExtValid = true; break; }"); Output.WriteLine(Extra_Indent + " }"); if (Version == UploadiFive_Version_Enum.HTML5) { if (DisallowedFileExtenstionMessage.Length > 0) { Output.WriteLine(Extra_Indent + " if ( !isExtValid ) { alert(\"" + DisallowedFileExtenstionMessage + "\".replace('<extension>', ext)); $('#" + FileInputID + "').uploadifive('cancel', file); }"); } else { Output.WriteLine(Extra_Indent + " if ( !isExtValid ) { $('#" + FileInputID + "').uploadifive('cancel', file); }"); } } else { if (DisallowedFileExtenstionMessage.Length > 0) { Output.WriteLine(Extra_Indent + " if ( !isExtValid ) { alert(\"" + DisallowedFileExtenstionMessage + "\".replace('<extension>', ext)); $('#" + FileInputID + "').uploadify('cancel', '*'); }"); } else { Output.WriteLine(Extra_Indent + " if ( !isExtValid ) { $('#" + FileInputID + "').uploadify('cancel', '*'); }"); } } Output.WriteLine(Extra_Indent + " },"); } // Set the upload script and finish this if (Version == UploadiFive_Version_Enum.HTML5) { Output.Write(Extra_Indent + " 'uploadScript': '" + UploadScript + "'"); } else { if (String.IsNullOrEmpty(Swf)) { Output.WriteLine(Extra_Indent + " 'swf': 'uploadify/uploadify.swf',"); } else { Output.WriteLine(Extra_Indent + " 'swf': '" + Swf + "',"); } Output.Write(Extra_Indent + " 'uploader': '" + UploadScript + "'"); } if ((Version == UploadiFive_Version_Enum.HTML5) && (RevertToFlashVersion)) { // ENd the last line, with a paranthesis Output.WriteLine(","); Output.WriteLine(Extra_Indent + " 'onFallback': function() {"); Output.WriteLine(Extra_Indent + " // Revert to flash version if no HTML5"); // Switch to SWF version Version = UploadiFive_Version_Enum.Flash; string buttonCss = ButtonClass; if (!String.IsNullOrEmpty(RevertedButtonClass)) { ButtonClass = RevertedButtonClass; } try { Add_To_Stream(Output, Extra_Indent + " ", NoHtml5OrFlashMessage); Output.WriteLine("} //end"); } catch { // Just want to ensure the setting is returned } finally { Version = UploadiFive_Version_Enum.HTML5; ButtonClass = buttonCss; } } else { if (!String.IsNullOrEmpty(NoHtml5OrFlashMessage)) { // ENd the last line, with a paranthesis Output.WriteLine(","); Output.WriteLine(Extra_Indent + " 'onFallback': function() { alert('" + NoHtml5OrFlashMessage.Replace("'", "") + "'); }"); } else { // End the last line Output.WriteLine(); } } Output.WriteLine(Extra_Indent + " });"); Output.WriteLine(); }