public ActionResult ReturnDataContext(HttpContext context) { FilesStatus fs = new FilesStatus(); return(View()); }
public JsonResult Upload(int?productId = 0) { var statuses = new List <FilesStatus>(); if (Request.Files != null && Request.Files.Count > 0) { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[0]; string fileName = Path.GetFileName(file.FileName); string folerName = "ClaimId"; string uploadFoler = Server.MapPath("/Content/File/Document/") + folerName; if (!Directory.Exists(uploadFoler)) { Directory.CreateDirectory(uploadFoler); } var filePath = Path.Combine(uploadFoler, fileName); if (System.IO.File.Exists(filePath)) { int k = 1; do { fileName = string.Format("{0}{1}{2}", Path.GetFileNameWithoutExtension(file.FileName), k, Path.GetExtension(fileName)); filePath = Path.Combine(uploadFoler, fileName); k++; }while (System.IO.File.Exists(filePath)); } file.SaveAs(filePath); var fileUrl = Path.Combine(folerName, fileName); DocFile docFile = new DocFile(); docFile.ProductId = 1; docFile.FileName = fileName; docFile.FileUrl = fileUrl; docFile.FileSuffix = Path.GetExtension(fileName); if (file.ContentLength < 1024 * 1024) { docFile.FileSize = (file.ContentLength / 1024f).ToString("0.00") + "KB"; } else { docFile.FileSize = ((file.ContentLength / 1024f) / 1024f).ToString("0.00") + "MB"; } docFile.CreaterId = 1; docFile.UpdatedOn = docFile.CreatedOn = DateTime.UtcNow; docFile.UpdatedBy = docFile.CreatedBy = "System"; context.DocFile.InsertOnSubmit(docFile); context.SubmitChanges(); FilesStatus fileStatus = new FilesStatus(file.FileName, file.ContentLength); statuses.Add(fileStatus); } } return(Json(statuses)); }
/// <summary> /// Uploads a partial file to the server. /// </summary> /// <param name="fileName"> The file name. </param> /// <param name="prefix"> The prefix of the fields to be placed in the HTML. </param> /// <param name="location"> The storage location for the temporary file. </param> /// <returns> The <see cref="ActionResult"/> containing information about execution of the upload. </returns> /// <exception cref="HttpRequestValidationException"> When more than one file is uploaded, or when the file is null. </exception> private ActionResult UploadPartialFile(string fileName, string prefix, string location, string tag) { // todo: partial file upload is not yet supported if (this.Request.Files.Count != 1) { throw new HttpRequestValidationException( "Attempt to upload chunked file containing more than one fragment per request"); } var httpPostedFileBase = this.Request.Files[0]; if (httpPostedFileBase == null) { throw new HttpRequestValidationException("Posted file is null."); } var inputStream = httpPostedFileBase.InputStream; fileName = Path.GetFileName(fileName); Debug.Assert(fileName != null, "fileName != null"); var fullLocation = new BlobLocation(Path.Combine(location, fileName)); // todo: Must append to blob block // this.storage.CreateOrAppendToFile(fullPath, inputStream); var fileLength = (long)this.storage.GetFileLength(fullLocation.ContainerName, fullLocation.BlobName); // todo: must create a valid file metadata, or retrieve an already existing one from the database int id = 0; var fileStatus = new FilesStatus(id, fileName, fileLength, prefix); // when doing partial upload of a file, no thumb-image will be generated // also the file wont display in the gallery (because no url will be provided) if (StringHelper.IsDocumentFileName(fileName)) { fileStatus.IconClass = "document-file-icon"; } else { fileStatus.IconClass = "generic-file-icon"; } fileStatus.UrlLarge = null; // cannot download when it is a partial uploaded file fileStatus.UrlFull = null; return(this.JsonIframeSafe(new { files = new[] { fileStatus } })); }
public HttpResponseMessage PostFileNew() { //TODO:upload error handle HttpResponseMessage result = null; var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { //var docfiles = new List<string>(); //foreach (string file in httpRequest.Files) //string file = httpRequest.Files[0]; //{ var postedFile = httpRequest.Files[0]; var filePath = HttpContext.Current.Server.MapPath("~/TempFiles/" + Path.GetFileName(postedFile.FileName)); postedFile.SaveAs(filePath); /* * try * { * * docfiles.Add(filePath); * } * catch (Exception ex) * { * * result = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); * } */ //} FilesStatus f = new FilesStatus(); f.name = postedFile.FileName; f.url = "api/upload/" + postedFile.FileName; f.thumbnail_url = @"data:image/png;base64," + EncodeFile(filePath); result = Request.CreateResponse(HttpStatusCode.Created, f); } else { result = Request.CreateResponse(HttpStatusCode.BadRequest); } return(result); }
// Upload entire file private void UploadWholeFile(HttpContext context, List <FilesStatus> statuses, string folderName) { for (int i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; var fullPath = StorageRoot + folderName + "\\" + folderName + '_' + Path.GetFileName(file.FileName); var folderPath = StorageRoot + folderName; if (!File.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } var ext = Path.GetExtension(fullPath); file.SaveAs(fullPath); string fullName = Path.GetFileName(file.FileName); FilesStatus status = new FilesStatus(fullName, file.ContentLength, fullPath); string path = Path.GetFullPath(fullPath); DB.UploadHandlertbl.Add(new UploadHandlerModel { FileName = status.name, FileType = status.type, Size = status.size, URL = status.url, Delete_Type = status.delete_type, Delete_Url = status.delete_url, Error = status.error, Progress = status.progress, Thumbnail_Url = status.thumbnail_url, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString() }); DataSync(folderName, status, path); //statuses.Add(new FilesStatus(fullName, file.ContentLength, fullPath)); } DB.SaveChanges(); }
public ActionResult UploadAgreement() { var resultList = new List <FilesStatus>(); var filesToUpload = this.HttpContext.Request.Files; var uploadHelper = new RentalAgreements(); Agreement newAgreement; for (int i = 0; i < filesToUpload.Count; i++) { newAgreement = uploadHelper.Upload(filesToUpload[i], User.Identity.Name, HttpContext); if (newAgreement != null) { var status = new FilesStatus() { thumbnail_url = Url.Content("~/User/GetThumb/") + newAgreement.Id, url = Url.Content("~/User/GetAgreement/") + newAgreement.Id, name = newAgreement.FileName, size = filesToUpload[i].ContentLength, type = filesToUpload[i].ContentType, delete_url = Url.Content("~/User/DeleteAgreement/") + newAgreement.Id, delete_type = "POST", progress = "1.0" }; resultList.Add(status); db.Agreements.Add(newAgreement); db.SaveChanges(); } } var resultStatus = new UploadRentalAgreementViewModel() { Status = resultList }; return(Json(resultList)); }
public FilesStatus FilesStatus(string basePath, string fileName, long fileLength, string type, SaveFileResult saveFileResult) { var filesStatus = new FilesStatus { Id = saveFileResult.Id, SiteId = saveFileResult.SiteId, Name = fileName, Type = type, PropertyName = saveFileResult.PropertyName, Size = fileLength }; if (!string.IsNullOrEmpty(saveFileResult.Url)) { filesStatus.Url = basePath + "api/file/get/" + saveFileResult.SiteId + "/" + saveFileResult.Id + "/ImageUploaded/" + fileName; } filesStatus.DeleteUrl = basePath + "api/file/delete/" + saveFileResult.SiteId + "/" + saveFileResult.Id + "/" + fileName; filesStatus.DeleteType = "DELETE"; filesStatus.ThumbnailUrl = basePath + "api/file/get/" + saveFileResult.SiteId + "/" + saveFileResult.Id + "/ImageThumb/" + fileName; filesStatus.IsTemporary = true; filesStatus.Detail = new FileDetail { ImageSize = saveFileResult.ImageUploadedSize, Url = filesStatus.Url, Size = fileLength }; filesStatus.Detail = new FileDetail { ImageSize = saveFileResult.ImageThumbSize, Url = filesStatus.ThumbnailUrl }; return(filesStatus); }
private void DataSync(string folderName, FilesStatus status, string path) { switch (folderName) { case "品牌传播曝光度分析-每日数据导入": var text = File.ReadAllText(path, System.Text.Encoding.UTF8); JObject obj = JObject.Parse(text); string data = obj["series"].ToString(); string xAxis = obj["xAxis"].ToString(); string t_month = obj["date"].ToString(); int i = status.name.IndexOf('-', 0); string brand_name = status.name.Substring(0, i); string year = obj["date"].ToString().Substring(0, 4); string mon = ""; if (obj["date"].ToString().Length == 8) { mon = obj["date"].ToString().Substring(5, 2); } else { mon = obj["date"].ToString().Substring(5, 1); mon = '0' + mon; } t_month = year + mon; int month = Convert.ToInt32(t_month); string file_name = status.name.Replace("(一个月).txt", ""); DB.BrandExposureLinetbl.Add(new BrandExposureLine { ChartID = 1, BrandName = brand_name, Series = data, xAxis = xAxis, Month = month, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString(), }); break; case "品牌传播曝光度分析-每月数据导入": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["series"].ToString(); DB.BrandExposureBubbletbl.Add(new BrandExposureBubble { ChartID = 2, BrandName = file_name, Series = data, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString(), }); break; case "品牌传播曝光度分析微博论坛数据": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["data"].ToString(); if (obj["data"]["wordgraph"][0]["features"].ToString() == "[]") { break; } int period = Convert.ToInt32(obj["date"].ToString()); DB.BrandSpreadMapBlogtbl.Add(new BrandSpreadMapBlog { Content = text, Period = period, BrandName = file_name, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString() }); break; case "品牌关键字分析新闻数据": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["data"].ToString(); if (obj["data"]["wordgraph"][0]["features"].ToString() == "[]") { break; } period = Convert.ToInt32(obj["date"].ToString()); DB.BrandSpreadMapNewstbl.Add(new BrandSpreadMapNews { Content = text, Period = period, BrandName = file_name, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString() }); break; case "品牌关键字分析微博论坛数据": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["data"].ToString(); if (obj["data"]["wordgraph"][0]["features"].ToString() == "[]") { break; } period = Convert.ToInt32(obj["date"].ToString()); DB.BrandSpreadMapBlogtbl.Add(new BrandSpreadMapBlog { Content = text, Period = period, BrandName = file_name, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString() }); break; case "品牌形象分析论坛微博数据": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["series"].ToString(); xAxis = obj["xAxis"].ToString(); DB.BrandImageBlogtbl.Add(new BrandImageBlog { ChartID = 3, BrandName = file_name, Series = data, xAxis = xAxis, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString(), }); break; case "品牌形象分析新闻数据": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["series"].ToString(); xAxis = obj["xAxis"].ToString(); DB.BrandImageNewstbl.Add(new BrandImageNews { ChartID = 3, BrandName = file_name, Series = data, xAxis = xAxis, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString(), }); break; case "设计感与功能性分析图": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["series"].ToString(); xAxis = obj["xAxis"].ToString(); DB.DesignSensetbl.Add(new DesignSense { ChartID = 3, BrandName = file_name, Series = data, xAxis = xAxis, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString(), }); break; case "品牌用户属性分析(性别)": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["series"].ToString(); DB.SexRatiotbl.Add(new SexRatio { ChartID = 4, BrandName = file_name, Series = data, LastModifed = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString(), }); break; case "品牌关注点分析论坛微博数据": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["series"].ToString(); xAxis = obj["xAxis"].ToString(); month = int.Parse(obj["series"]["Month"].ToString()); DB.BrandFocusBlogtbl.Add(new BrandFocusBlog { ChartID = 3, BrandName = file_name, Month = month, Series = data, xAxis = xAxis, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString(), }); break; case "品牌关注点分析新闻数据": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); data = obj["series"].ToString(); xAxis = obj["xAxis"].ToString(); month = int.Parse(obj["series"]["Month"].ToString()); DB.BrandFocusNewstbl.Add(new BrandFocusNews { ChartID = 3, BrandName = file_name, Month = month, Series = data, xAxis = xAxis, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString(), }); break; case "媒体关注度分析图谱": text = File.ReadAllText(path, System.Text.Encoding.UTF8); obj = JObject.Parse(text); file_name = status.name.Replace(".txt", ""); period = Convert.ToInt32(obj["date"].ToString()); if (obj["data"]["wordgraph"][0]["features"].ToString() == "[]") { break; } DB.MediaFocusMaptbl.Add(new MediaFocusMap { Content = text, Period = period, BrandName = file_name, LastModified = DateTime.Now, LastModifiedBy = Membership.GetUser().UserName.ToString(), }); break; default: break; } }
public FilesStatus GetFilesStatus(PatientFileViewModel fileModel, string prefix) { var fileName = fileModel.SourceFileName; var containerName = fileModel.ContainerName; var sourceFileName = Path.GetFileName(fileModel.SourceFileName ?? "") ?? ""; var normalFileName = StringHelper.RemoveDiacritics(sourceFileName.ToLowerInvariant()); var fileNamePrefix = Path.GetDirectoryName(fileModel.BlobName) + "\\"; var fullStoragePath = string.Format("{0}\\{1}file-{2}-{3}", containerName, fileNamePrefix, fileModel.Id, normalFileName); var fileStatus = new FilesStatus(fileModel.Id, fileModel.MetadataId, fileName, fileModel.FileLength, prefix, fileModel.FileTitle); var isPatientFiles = Regex.IsMatch(fileModel.ContainerName, @"^patient-files-\d+$"); // Validating each file location... otherwise this could be a security hole. if (!isPatientFiles) throw new Exception("Invalid file location for patient files."); var fileMetadataProvider = new DbFileMetadataProvider(this.db, this.datetimeService, this.DbUser.PracticeId); bool imageThumbOk = false; try { var thumbName = string.Format("{0}\\{1}file-{2}-thumb-{4}x{5}-{3}", containerName, fileNamePrefix, fileModel.MetadataId, normalFileName, 120, 120); var thumbResult = ImageHelper.TryGetOrCreateThumb(fileModel.MetadataId, 120, 120, fullStoragePath, thumbName, true, storage, fileMetadataProvider); if (thumbResult.Status == CreateThumbStatus.Ok) { fileStatus.ThumbnailUrl = @"data:" + thumbResult.ContentType + ";base64," + Convert.ToBase64String(thumbResult.Data); fileStatus.IsInGallery = true; imageThumbOk = true; } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { } if (!imageThumbOk) { if (StringHelper.IsDocumentFileName(fileName)) { fileStatus.IconClass = "document-file-icon"; } else { fileStatus.IconClass = "generic-file-icon"; } } bool isTemp = fileModel.Id == null; if (isTemp) { var location = string.Format("{0}\\{1}", fileModel.ContainerName, fileModel.BlobName); if (imageThumbOk) fileStatus.UrlLarge = this.Url.Action("Image", "TempFile", new { w = 1024, h = 768, id = fileModel.MetadataId, location }); fileStatus.UrlFull = this.Url.Action("File", "TempFile", new { id = fileModel.MetadataId, location }); } else { if (imageThumbOk) fileStatus.UrlLarge = this.Url.Action("Image", "PatientFiles", new { w = 1024, h = 768, id = fileModel.Id }); fileStatus.UrlFull = this.Url.Action("File", "PatientFiles", new { id = fileModel.Id }); } return fileStatus; }
/// <summary> /// Upload whole file. /// </summary> /// <param name="prefix"> The prefix of the fields to be placed in the HTML. </param> /// <param name="location"> The location where the temporary file should be stored. </param> /// <returns> The <see cref="ActionResult"/> containing information about execution of the upload. </returns> private ActionResult UploadWholeFile(string prefix, string location, string tag) { var statuses = new List <FilesStatus>(); for (int i = 0; i < this.Request.Files.Count; i++) { var file = this.Request.Files[i]; Debug.Assert(file != null, "file != null"); var containerName = location.Split("\\".ToCharArray(), 2).FirstOrDefault(); var sourceFileName = Path.GetFileName(file.FileName ?? "") ?? ""; var normalFileName = StringHelper.NormalizeFileName(sourceFileName); var fileNamePrefix = location.Split("\\".ToCharArray(), 2).Skip(1).FirstOrDefault(); var fileExpirationDate = this.datetimeService.UtcNow + TimeSpan.FromDays(file.ContentLength < 10 * 1024000 ? 2 : 10); Debug.Assert(sourceFileName != null, "sourceFileName != null"); var metadataProvider = new DbFileMetadataProvider(this.db, this.datetimeService, this.DbUser.PracticeId); // creating the metadata entry for the main file FileMetadata metadata = metadataProvider.CreateTemporary( containerName, sourceFileName, string.Format("{0}file-{1}-{2}", fileNamePrefix, "{id}", normalFileName), fileExpirationDate, this.DbUser.Id, tag, formatWithId: true); metadata.OwnerUserId = this.DbUser.Id; metadataProvider.SaveChanges(); // saving the file to the storage this.storage.UploadFileToStorage(file.InputStream, containerName, metadata.BlobName); // returning information to the client var fileStatus = new FilesStatus(metadata.Id, sourceFileName, file.ContentLength, prefix); bool imageThumbOk = false; try { var fullStoragePath = string.Format("{0}\\{1}", containerName, metadata.BlobName); var thumbName = string.Format("{0}\\{1}file-{2}-thumb-{4}x{5}-{3}", containerName, fileNamePrefix, metadata.Id, normalFileName, 120, 120); var thumbResult = ImageHelper.TryGetOrCreateThumb(metadata.Id, 120, 120, fullStoragePath, thumbName, true, this.storage, metadataProvider); if (thumbResult.Status == CreateThumbStatus.Ok) { fileStatus.ThumbnailUrl = @"data:" + thumbResult.ContentType + ";base64," + Convert.ToBase64String(thumbResult.Data); fileStatus.IsInGallery = true; imageThumbOk = true; } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { } if (!imageThumbOk) { if (StringHelper.IsDocumentFileName(sourceFileName)) { fileStatus.IconClass = "document-file-icon"; } else { fileStatus.IconClass = "generic-file-icon"; } } else { fileStatus.UrlLarge = this.Url.Action("Image", new { w = 1024, h = 768, location, metadata.Id }); } fileStatus.UrlFull = this.Url.Action("File", new { location, metadata.Id }); fileStatus.DeleteUrl = this.Url.Action("Index", new { location, metadata.Id }); statuses.Add(fileStatus); } return(this.JsonIframeSafe(new { files = statuses })); }
public FilesStatus GetFilesStatus(PatientFileViewModel fileModel, string prefix) { var fileName = fileModel.SourceFileName; var containerName = fileModel.ContainerName; var sourceFileName = Path.GetFileName(fileModel.SourceFileName ?? "") ?? ""; var normalFileName = StringHelper.RemoveDiacritics(sourceFileName.ToLowerInvariant()); var fileNamePrefix = Path.GetDirectoryName(fileModel.BlobName) + "\\"; var fullStoragePath = string.Format("{0}\\{1}file-{2}-{3}", containerName, fileNamePrefix, fileModel.Id, normalFileName); var fileStatus = new FilesStatus(fileModel.Id, fileModel.MetadataId, fileName, fileModel.FileLength, prefix, fileModel.FileTitle); var isPatientFiles = Regex.IsMatch(fileModel.ContainerName, @"^patient-files-\d+$"); // Validating each file location... otherwise this could be a security hole. if (!isPatientFiles) { throw new Exception("Invalid file location for patient files."); } var fileMetadataProvider = new DbFileMetadataProvider(this.db, this.datetimeService, this.DbUser.PracticeId); bool imageThumbOk = false; try { var thumbName = string.Format("{0}\\{1}file-{2}-thumb-{4}x{5}-{3}", containerName, fileNamePrefix, fileModel.MetadataId, normalFileName, 120, 120); var thumbResult = ImageHelper.TryGetOrCreateThumb(fileModel.MetadataId, 120, 120, fullStoragePath, thumbName, true, storage, fileMetadataProvider); if (thumbResult.Status == CreateThumbStatus.Ok) { fileStatus.ThumbnailUrl = @"data:" + thumbResult.ContentType + ";base64," + Convert.ToBase64String(thumbResult.Data); fileStatus.IsInGallery = true; imageThumbOk = true; } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { } if (!imageThumbOk) { if (StringHelper.IsDocumentFileName(fileName)) { fileStatus.IconClass = "document-file-icon"; } else { fileStatus.IconClass = "generic-file-icon"; } } bool isTemp = fileModel.Id == null; if (isTemp) { var location = string.Format("{0}\\{1}", fileModel.ContainerName, fileModel.BlobName); if (imageThumbOk) { fileStatus.UrlLarge = this.Url.Action("Image", "TempFile", new { w = 1024, h = 768, id = fileModel.MetadataId, location }); } fileStatus.UrlFull = this.Url.Action("File", "TempFile", new { id = fileModel.MetadataId, location }); } else { if (imageThumbOk) { fileStatus.UrlLarge = this.Url.Action("Image", "PatientFiles", new { w = 1024, h = 768, id = fileModel.Id }); } fileStatus.UrlFull = this.Url.Action("File", "PatientFiles", new { id = fileModel.Id }); } return(fileStatus); }
/// <summary> /// Upload whole file. /// </summary> /// <param name="prefix"> The prefix of the fields to be placed in the HTML. </param> /// <param name="location"> The location where the temporary file should be stored. </param> /// <returns> The <see cref="ActionResult"/> containing information about execution of the upload. </returns> private ActionResult UploadWholeFile(string prefix, string location, string tag) { var statuses = new List<FilesStatus>(); for (int i = 0; i < this.Request.Files.Count; i++) { var file = this.Request.Files[i]; Debug.Assert(file != null, "file != null"); var containerName = location.Split("\\".ToCharArray(), 2).FirstOrDefault(); var sourceFileName = Path.GetFileName(file.FileName ?? "") ?? ""; var normalFileName = StringHelper.NormalizeFileName(sourceFileName); var fileNamePrefix = location.Split("\\".ToCharArray(), 2).Skip(1).FirstOrDefault(); var fileExpirationDate = this.datetimeService.UtcNow + TimeSpan.FromDays(file.ContentLength < 10 * 1024000 ? 2 : 10); Debug.Assert(sourceFileName != null, "sourceFileName != null"); var metadataProvider = new DbFileMetadataProvider(this.db, this.datetimeService, this.DbUser.PracticeId); // creating the metadata entry for the main file FileMetadata metadata = metadataProvider.CreateTemporary( containerName, sourceFileName, string.Format("{0}file-{1}-{2}", fileNamePrefix, "{id}", normalFileName), fileExpirationDate, this.DbUser.Id, tag, formatWithId: true); metadata.OwnerUserId = this.DbUser.Id; metadataProvider.SaveChanges(); // saving the file to the storage this.storage.UploadFileToStorage(file.InputStream, containerName, metadata.BlobName); // returning information to the client var fileStatus = new FilesStatus(metadata.Id, sourceFileName, file.ContentLength, prefix); bool imageThumbOk = false; try { var fullStoragePath = string.Format("{0}\\{1}", containerName, metadata.BlobName); var thumbName = string.Format("{0}\\{1}file-{2}-thumb-{4}x{5}-{3}", containerName, fileNamePrefix, metadata.Id, normalFileName, 120, 120); var thumbResult = ImageHelper.TryGetOrCreateThumb(metadata.Id, 120, 120, fullStoragePath, thumbName, true, this.storage, metadataProvider); if (thumbResult.Status == CreateThumbStatus.Ok) { fileStatus.ThumbnailUrl = @"data:" + thumbResult.ContentType + ";base64," + Convert.ToBase64String(thumbResult.Data); fileStatus.IsInGallery = true; imageThumbOk = true; } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { } if (!imageThumbOk) { if (StringHelper.IsDocumentFileName(sourceFileName)) { fileStatus.IconClass = "document-file-icon"; } else { fileStatus.IconClass = "generic-file-icon"; } } else { fileStatus.UrlLarge = this.Url.Action("Image", new { w = 1024, h = 768, location, metadata.Id }); } fileStatus.UrlFull = this.Url.Action("File", new { location, metadata.Id }); fileStatus.DeleteUrl = this.Url.Action("Index", new { location, metadata.Id }); statuses.Add(fileStatus); } return this.JsonIframeSafe(new { files = statuses }); }
/// <summary> /// Uploads a partial file to the server. /// </summary> /// <param name="fileName"> The file name. </param> /// <param name="prefix"> The prefix of the fields to be placed in the HTML. </param> /// <param name="location"> The storage location for the temporary file. </param> /// <returns> The <see cref="ActionResult"/> containing information about execution of the upload. </returns> /// <exception cref="HttpRequestValidationException"> When more than one file is uploaded, or when the file is null. </exception> private ActionResult UploadPartialFile(string fileName, string prefix, string location, string tag) { // todo: partial file upload is not yet supported if (this.Request.Files.Count != 1) throw new HttpRequestValidationException( "Attempt to upload chunked file containing more than one fragment per request"); var httpPostedFileBase = this.Request.Files[0]; if (httpPostedFileBase == null) throw new HttpRequestValidationException("Posted file is null."); var inputStream = httpPostedFileBase.InputStream; fileName = Path.GetFileName(fileName); Debug.Assert(fileName != null, "fileName != null"); var fullLocation = new BlobLocation(Path.Combine(location, fileName)); // todo: Must append to blob block // this.storage.CreateOrAppendToFile(fullPath, inputStream); var fileLength = (long)this.storage.GetFileLength(fullLocation.ContainerName, fullLocation.BlobName); // todo: must create a valid file metadata, or retrieve an already existing one from the database int id = 0; var fileStatus = new FilesStatus(id, fileName, fileLength, prefix); // when doing partial upload of a file, no thumb-image will be generated // also the file wont display in the gallery (because no url will be provided) if (StringHelper.IsDocumentFileName(fileName)) { fileStatus.IconClass = "document-file-icon"; } else { fileStatus.IconClass = "generic-file-icon"; } fileStatus.UrlLarge = null; // cannot download when it is a partial uploaded file fileStatus.UrlFull = null; return this.JsonIframeSafe(new { files = new[] { fileStatus } }); }