/// <summary> /// Adds the uploaded files to the gallery. This method is called when the application is operating under full trust. In this case, /// the ComponentArt Upload control is used. The logic is nearly identical to that in AddUploadedFilesLessThanFullTrust - the only /// differences are syntax differences arising from the different file upload control. /// </summary> /// <param name="files">The files to add to the gallery.</param> private void AddUploadedFilesForFullTrust(UploadedFileInfoCollection files) { // Clear the list of hash keys so we're starting with a fresh load from the data store. try { MediaObjectHashKeys.Clear(); string albumPhysicalPath = this.GetAlbum().FullPhysicalPathOnDisk; HelperFunctions.BeginTransaction(); UploadedFileInfo[] fileInfos = new UploadedFileInfo[files.Count]; files.CopyTo(fileInfos, 0); Array.Reverse(fileInfos); foreach (UploadedFileInfo file in fileInfos) { if (String.IsNullOrEmpty(file.FileName)) continue; if ((System.IO.Path.GetExtension(file.FileName).ToUpperInvariant() == ".ZIP") && (!chkDoNotExtractZipFile.Checked)) { #region Extract the files from the zipped file. lock (file) { if (File.Exists(file.TempFileName)) { string userName = (String.IsNullOrEmpty(User.Identity.Name) ? "Anonymous" : User.Identity.Name); using (ZipUtility zip = new ZipUtility(userName, WebsiteController.GetRolesForUser(), User.Identity.IsAuthenticated)) { this._skippedFiles.AddRange(zip.ExtractZipFile(file.GetStream(), this.GetAlbum())); } } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair<string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } #endregion } else { #region Add the file string filename = HelperFunctions.ValidateFileName(albumPhysicalPath, file.FileName); string filepath = Path.Combine(albumPhysicalPath, filename); #if DEBUG TechInfoSystems.TracingTools.Tools.MarkSpot(string.Format(CultureInfo.CurrentCulture, "Attempting to move file {0} to {1}...", file.FileName, filepath)); #endif lock (file) { if (File.Exists(file.TempFileName)) { file.SaveAs(filepath); } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair<string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } try { IGalleryObject go = Factory.CreateMediaObjectInstance(filepath, this.GetAlbum()); WebsiteController.SaveGalleryObject(go); } catch (UnsupportedMediaObjectTypeException ex) { File.Delete(filepath); this._skippedFiles.Add(new KeyValuePair<string, string>(filename, ex.Message)); } #endregion } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } finally { // Delete the uploaded temporary files, as by this time they have been saved to the destination directory. foreach (UploadedFileInfo file in files) { System.IO.File.Delete(file.TempFileName); } // Clear the list of hash keys to free up memory. MediaObjectHashKeys.Clear(); HelperFunctions.PurgeCache(); } }
private static string SaveFileToTempDirectory(UploadedFileInfo fileToRestore) { // Save file to temp directory, ensuring that we are not overwriting an existing file. If the uploaded file is a ZIP archive, // extract the embedded XML file and save that. string filePath; if (Path.GetExtension(fileToRestore.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) { using (ZipUtility zip = new ZipUtility(Utils.UserName, RoleController.GetGalleryServerRolesForUser())) { filePath = zip.ExtractNextFileFromZip(fileToRestore.GetStream(), AppSetting.Instance.TempUploadDirectory); } } else { string fileName = HelperFunctions.ValidateFileName(AppSetting.Instance.TempUploadDirectory, fileToRestore.FileName); filePath = Path.Combine(AppSetting.Instance.TempUploadDirectory, fileName); fileToRestore.SaveAs(filePath); } return filePath; }
/// <summary> /// Adds the uploaded files to the gallery. This method is called when the application is operating under full trust. In this case, /// the ComponentArt Upload control is used. The logic is nearly identical to that in AddUploadedFilesLessThanFullTrust - the only /// differences are syntax differences arising from the different file upload control. /// </summary> /// <param name="files">The files to add to the gallery.</param> private void AddUploadedFilesForFullTrust(UploadedFileInfoCollection files) { // Clear the list of hash keys so we're starting with a fresh load from the data store. try { MediaObjectHashKeys.Clear(); string albumPhysicalPath = this.GetAlbum().FullPhysicalPathOnDisk; HelperFunctions.BeginTransaction(); UploadedFileInfo[] fileInfos = new UploadedFileInfo[files.Count]; files.CopyTo(fileInfos, 0); Array.Reverse(fileInfos); foreach (UploadedFileInfo file in fileInfos) { if (String.IsNullOrEmpty(file.FileName)) continue; if ((System.IO.Path.GetExtension(file.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (!chkDoNotExtractZipFile.Checked)) { #region Extract the files from the zipped file. lock (file) { if (File.Exists(file.TempFileName)) { using (ZipUtility zip = new ZipUtility(Utils.UserName, GetGalleryServerRolesForUser())) { this._skippedFiles.AddRange(zip.ExtractZipFile(file.GetStream(), this.GetAlbum(), chkDiscardOriginalImage.Checked)); } } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair<string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } #endregion } else { #region Add the file string filename = HelperFunctions.ValidateFileName(albumPhysicalPath, file.FileName); string filepath = Path.Combine(albumPhysicalPath, filename); lock (file) { if (File.Exists(file.TempFileName)) { file.SaveAs(filepath); } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair<string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } try { using (IGalleryObject go = Factory.CreateMediaObjectInstance(filepath, this.GetAlbum())) { GalleryObjectController.SaveGalleryObject(go); Business.Image img = go as Business.Image; bool isImage = (img != null); if ((chkDiscardOriginalImage.Checked) && isImage) { img.DeleteHiResImage(); GalleryObjectController.SaveGalleryObject(img); } } } catch (UnsupportedMediaObjectTypeException ex) { try { File.Delete(filepath); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance this._skippedFiles.Add(new KeyValuePair<string, string>(filename, ex.Message)); } #endregion } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } finally { // Delete the uploaded temporary files, as by this time they have been saved to the destination directory. foreach (UploadedFileInfo file in files) { try { System.IO.File.Delete(file.TempFileName); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance } // Clear the list of hash keys to free up memory. MediaObjectHashKeys.Clear(); HelperFunctions.PurgeCache(); } }
private static string SaveFileToTempDirectory(UploadedFileInfo fileToRestore) { // Save file to temp directory, ensuring that we are not overwriting an existing file. string newFileName = fileToRestore.FileName; int uniqueId = 0; while (File.Exists(Path.Combine(AppSetting.Instance.TempUploadDirectory, newFileName))) { if (fileToRestore.Extension != String.Empty) { newFileName = fileToRestore.FileName.Replace("." + fileToRestore.Extension, "(" + uniqueId + ")." + fileToRestore.Extension); } else { newFileName = fileToRestore.FileName + "(" + uniqueId + ")"; } uniqueId++; } string filePath = Path.Combine(AppSetting.Instance.TempUploadDirectory, newFileName); fileToRestore.SaveAs(filePath); return filePath; }
/// <summary> /// Adds the uploaded files to the gallery. This method is called when the application is operating under full trust. In this case, /// the ComponentArt Upload control is used. The logic is nearly identical to that in AddUploadedFilesLessThanFullTrust - the only /// differences are syntax differences arising from the different file upload control. /// </summary> /// <param name="files">The files to add to the gallery.</param> private void AddUploadedFilesForFullTrust(UploadedFileInfoCollection files) { // Clear the list of hash keys so we're starting with a fresh load from the data store. try { MediaObjectHashKeys.Clear(); string albumPhysicalPath = this.GetAlbum().FullPhysicalPathOnDisk; HelperFunctions.BeginTransaction(); UploadedFileInfo[] fileInfos = new UploadedFileInfo[files.Count]; files.CopyTo(fileInfos, 0); Array.Reverse(fileInfos); foreach (UploadedFileInfo file in fileInfos) { if (String.IsNullOrEmpty(file.FileName)) { continue; } if ((System.IO.Path.GetExtension(file.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (!chkDoNotExtractZipFile.Checked)) { #region Extract the files from the zipped file. lock (file) { if (File.Exists(file.TempFileName)) { using (ZipUtility zip = new ZipUtility(Util.UserName, GetGalleryServerRolesForUser())) { this._skippedFiles.AddRange(zip.ExtractZipFile(file.GetStream(), this.GetAlbum(), chkDiscardOriginalImage.Checked)); } } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair <string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } // Sueetie Modified - Add contents of ZIP file - All List <SueetieMediaObject> sueetieMediaObjects = SueetieMedia.GetSueetieMediaUpdateList(this.GetAlbumId()); int i = 0; foreach (SueetieMediaObject _sueetieMediaObject in sueetieMediaObjects) { int _moid = _sueetieMediaObject.MediaObjectID; IGalleryObject mo = Factory.LoadMediaObjectInstance(_moid); SueetieContent sueetieContent = new SueetieContent { SourceID = _sueetieMediaObject.MediaObjectID, ContentTypeID = MediaHelper.ConvertContentType(mo.MimeType.TypeCategory), ApplicationID = (int)SueetieApplications.Current.ApplicationID, UserID = _sueetieMediaObject.SueetieUserID, DateTimeCreated = mo.DateAdded, IsRestricted = mo.IsPrivate, Permalink = MediaHelper.SueetieMediaObjectUrl(_moid, this.GalleryId) }; // Add Sueetie-specific data to Sueetie_gs_MediaObject _sueetieMediaObject.ContentTypeID = MediaHelper.ConvertContentType(mo.MimeType.TypeCategory); _sueetieMediaObject.AlbumID = this.GetAlbum().Id; _sueetieMediaObject.InDownloadReport = false; SueetieMedia.CreateSueetieMediaObject(_sueetieMediaObject); SueetieCommon.AddSueetieContent(sueetieContent); i++; } #endregion } else { #region Add the file string filename = HelperFunctions.ValidateFileName(albumPhysicalPath, file.FileName); string filepath = Path.Combine(albumPhysicalPath, filename); lock (file) { if (File.Exists(file.TempFileName)) { file.SaveAs(filepath); } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair <string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } try { IGalleryObject go = Factory.CreateMediaObjectInstance(filepath, this.GetAlbum()); GalleryObjectController.SaveGalleryObject(go); if ((chkDiscardOriginalImage.Checked) && (go is Business.Image)) { ((Business.Image)go).DeleteHiResImage(); GalleryObjectController.SaveGalleryObject(go); } // Sueetie Modified - Add mediaobject to Sueetie_Content - Single File SueetieContent sueetieContent = new SueetieContent { SourceID = go.Id, ContentTypeID = MediaHelper.ConvertContentType(go.MimeType.TypeCategory), ApplicationID = (int)SueetieApplications.Current.ApplicationID, UserID = CurrentSueetieUserID, IsRestricted = this.GetAlbum().IsPrivate, Permalink = MediaHelper.SueetieMediaObjectUrl(go.Id, this.GalleryId) }; SueetieCommon.AddSueetieContent(sueetieContent); // Add Sueetie-specific data to Sueetie_gs_MediaObject SueetieMediaObject _sueetieMediaObject = new SueetieMediaObject(); _sueetieMediaObject.MediaObjectID = go.Id; _sueetieMediaObject.ContentTypeID = MediaHelper.ConvertContentType(go.MimeType.TypeCategory); _sueetieMediaObject.AlbumID = this.GetAlbum().Id; _sueetieMediaObject.InDownloadReport = false; SueetieMedia.CreateSueetieMediaObject(_sueetieMediaObject); SueetieMediaAlbum sueetieAlbum = SueetieMedia.GetSueetieMediaAlbum(this.GetAlbum().Id); if (CurrentSueetieGallery.IsLogged) { SueetieLogs.LogUserEntry((UserLogCategoryType)sueetieAlbum.AlbumMediaCategoryID, sueetieAlbum.ContentID, CurrentSueetieUserID); } } catch (UnsupportedMediaObjectTypeException ex) { try { File.Delete(filepath); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance this._skippedFiles.Add(new KeyValuePair <string, string>(filename, ex.Message)); } #endregion } } SueetieMedia.ClearMediaPhotoListCache(0); SueetieMedia.ClearSueetieMediaObjectListCache(this.CurrentSueetieGalleryID); HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } finally { // Delete the uploaded temporary files, as by this time they have been saved to the destination directory. foreach (UploadedFileInfo file in files) { try { System.IO.File.Delete(file.TempFileName); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance } // Clear the list of hash keys to free up memory. MediaObjectHashKeys.Clear(); HelperFunctions.PurgeCache(); } }
/// <summary> /// This method is used to handle a MemoryStream returned from the uploaded file, /// and the memory stream is going to be attempted to be converted to an Xml string. /// </summary> private void OnFileUploaded2(UploadedFileInfo uploadedFileInfo) { try { // if aborted if (uploadedFileInfo.Aborted) { // get the status XmlString = (MarkupString)uploadedFileInfo.ErrorMessage; } else { // if the MemoryStream was uploaded if (uploadedFileInfo.HasStream) { System.Text.Encoding encoding = System.Text.Encoding.UTF8; string temp = encoding.GetString(uploadedFileInfo.Stream.ToArray()); // Get the lines List <TextLine> lines = WordParser.GetTextLines(temp.TrimEnd()); // If the lines collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(lines)) { // local int count = 0; // Create the lines this.Lines = new List <XmlLine>(); // Iterate the collection of TextLine objects foreach (TextLine line in lines) { if (TextHelper.Exists(line.Text)) { // cast the XmlLine as a Line XmlLine xmlLine = new XmlLine(); // Set the properties xmlLine.Text = line.Text; // not the first line or the last line if (count != 0) { // Indent xmlLine.Indent = true; } // Add this line this.Lines.Add(xmlLine); // increment the count count++; } } // Make sure we indent this.Lines[this.Lines.Count - 1].Indent = false; } } } } catch (Exception error) { // for debugging only for this sample string err = error.ToString(); } finally { // Might be needed ? StateHasChanged(); } }
public async Task <IHttpActionResult> UploadImage(string fileName = "") { //Use a GUID in case the fileName is not specified if (fileName == "") { fileName = Guid.NewGuid().ToString(); } //Check if submitted content is of MIME Multi Part Content with Form-data in it? if (!Request.Content.IsMimeMultipartContent("form-data")) { return(BadRequest("Could not find file to upload")); } //Read the content in a InMemory Muli-Part Form Data format var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider()); //Get the first file var files = provider.Files; var uploadedFile = files[0]; //Extract the file extention var extension = ExtractExtension(uploadedFile); //Get the file's content type var contentType = uploadedFile.Headers.ContentType.ToString(); //create the full name of the image with the fileName and extension var imageName = string.Concat(fileName, extension); //Get the reference to the Blob Storage and upload the file there var storageConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"]; var storageAccount = CloudStorageAccount.Parse(storageConnectionString); var blobClient = storageAccount.CreateCloudBlobClient(); var container = blobClient.GetContainerReference("images"); container.CreateIfNotExists(); var blockBlob = container.GetBlockBlobReference(imageName); blockBlob.Properties.ContentType = contentType; using (var fileStream = await uploadedFile.ReadAsStreamAsync()) //as Stream is IDisposable { blockBlob.UploadFromStream(fileStream); } var airesult = await MakeRequest(blockBlob.Uri.ToString()); //insert to sharepoint list string siteUrl = ConfigurationManager.AppSettings["SiteURL"].ToString(); using (ClientContext ctx = new ClientContext(siteUrl)) { SecureString passWord = new SecureString(); string passwordText = ConfigurationManager.AppSettings["SitePassword"].ToString(); string usernameText = ConfigurationManager.AppSettings["SiteUsername"].ToString(); foreach (char c in passwordText.ToCharArray()) { passWord.AppendChar(c); } ctx.Credentials = new SharePointOnlineCredentials(usernameText, passWord); List list = ctx.Web.Lists.GetByTitle("PowerJoy"); ListItemCreationInformation info = new ListItemCreationInformation(); ListItem image = list.AddItem(info); image["Title"] = imageName; image["Url"] = blockBlob.Uri.ToString(); image["TrumpRating"] = string.Format("You look {0} like the President of America", airesult.TrumpMatch); image["Feeling"] = string.Format("Someone looks {0}", airesult.Emotion); image.Update(); ctx.ExecuteQuery(); } var fileInfo = new UploadedFileInfo { FileName = fileName, FileExtension = extension, ContentType = contentType, FileURL = blockBlob.Uri.ToString(), Emotion = airesult.Emotion, TrumpFactor = airesult.TrumpMatch }; return(Ok(fileInfo)); }