public static DocumentDomain GetDocumentById(int archiveId) { DocumentDomain doc = null; switch (archiveId) { case 1: doc = getDoc1(); break; case 2: doc = getDoc2(); break; case 3: doc = getDoc3(); break; default: doc = getDoc4(); break; } return(doc); }
public int UpdateDocument(DocumentDomain document) { if (document == null) { throw new NsiArgumentException(DocumentMessages.DocumentInvalidArgument); } return(_documentRepository.UpdateDocument(document)); }
public void GetDocumentById_Success() { DocumentDomain document = _documentManipulation.GetDocumentById(1, 1); Assert.AreEqual(1, document.DocumentId); Assert.AreEqual(1, document.FileTypeId); Assert.AreEqual(1, document.StorageTypeId); Assert.AreEqual("Test Document", document.Name); Assert.AreEqual("Test test test test", document.Description); Assert.AreEqual(100, document.FileSize); Assert.AreEqual("path", document.Path); Assert.AreEqual("location id test", document.LocationExternalId); }
public HttpResponseMessage GetDocumentById(int archiveId) { if (!ModelState.IsValid) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } DocumentDomain document = DocumentService.GetDocumentById(archiveId); var response = new ItemResponse <DocumentDomain> { Item = document }; return(Request.CreateResponse(HttpStatusCode.OK, response)); }
// ......................................................................................... public static DocumentDomain getDoc2() { DocumentDomain document = new DocumentDomain { DocumentId = 2, Title = "LA in 1857", Year = 1857, Contributor = "John", Description = "Picture of LA. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", ResourceUrl = "https://cdn.loc.gov/service/pnp/ds/03400/03470v.jpg", TypeId = Enums.DocumentType.Photo, SourceInstitution = "Library of Congress", InstitutionUrl = "https://www.loc.gov/" }; return(document); }
// ......................................................................................... public static DocumentDomain getDoc1() { DocumentDomain document = new DocumentDomain { DocumentId = 1, Title = "Orange County", Year = 1889, Contributor = "Carlos", Description = "This is a map of Orange County from 1889. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", ResourceUrl = "https://tile.loc.gov/image-services/iiif/service:gmd:gmd436:g4363:g4363o:la000032/full/pct:12.5/0/default.jpg", TypeId = Enums.DocumentType.Map, SourceInstitution = "Library of Congress", InstitutionUrl = "https://www.loc.gov/" }; return(document); }
public HttpResponseMessage Download(int id) { DocumentDomain document = this._documentManipulation.GetDocumentById(id, 1); var webClient = new WebClient(); byte[] byteContent = webClient.DownloadData(document.Path); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(byteContent) }; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = document.Name + '.' + this._fileTypeManipulation.GetFileExtensionById(document.FileTypeId).ToString() }; return(response); }
/// <summary> /// Deletes Document /// </summary> /// <returns><see cref="IHttpActionResult"/></returns> public IHttpActionResult Delete(int id) { try { if (id <= 0) { throw new NsiArgumentException(DocumentMessages.DocumentInvalidArgument); } var document = new DocumentDomain(); if (this._azureActive.Equals("true")) { document = _documentManipulation.GetDocumentById(id, 1); } else if (this._azureActive.Equals("false")) { document = _documentManipulation.GetDocumentById(id, 2); } var fileType = _fileTypeManipulation.GetFileExtensionById(document.FileTypeId); var documentName = document.Name + '.' + fileType; if (document.StorageTypeId == 1) { DeleteHelper.DeleteFileFromAzure(documentName); } else if (document.StorageTypeId == 2) { FileInfo fi = new FileInfo(document.Path); fi.Delete(); } var result = _documentManipulation.DeleteDocument(id); if (!result) { throw new NsiBaseException(string.Format(DocumentMessages.DocumentDeleteFailed)); } return(Ok(result)); } catch (Exception e) { return(BadRequest(e.Message)); } }
public static Document FromDomainModel(this Document obj, DocumentDomain domain) { if (obj == null) { obj = new Document(); } obj.DocumentId = domain.DocumentId; obj.Name = domain.Name; obj.Path = domain.Path; obj.FileSize = domain.FileSize; obj.ExternalId = domain.ExternalId; obj.LocationExternalId = domain.LocationExternalId; obj.DateCreated = domain.DateCreated; obj.StorageTypeId = domain.StorageTypeId; obj.FileTypeId = domain.FileTypeId; obj.Description = domain.Description; return(obj); }
/// <summary> /// Update Document /// </summary> /// <returns><see cref="IHttpActionResult"/></returns> public IHttpActionResult UpdateDocument([FromBody] DocumentDomain document) { try { if (document == null || document.DocumentId <= 0) { throw new NsiArgumentException(DocumentMessages.DocumentInvalidArgument); } var result = _documentManipulation.UpdateDocument(document); if (result <= 0) { throw new NsiBaseException(string.Format(DocumentMessages.DocumentUpdateFailed)); } return(Ok(result)); } catch (Exception e) { return(BadRequest(e.Message)); } }
public int UpdateDocument(DocumentDomain document) { if (document == null) { throw new NsiArgumentException(DocumentMessages.DocumentInvalidArgument); } if (!_context.Document.Any(x => x.DocumentId == document.DocumentId)) { throw new NsiArgumentException(DocumentMessages.DocumentInvalidId); } var documentDb = _context.Document.Where(x => x.DocumentId == document.DocumentId).FirstOrDefault().FromDomainModel(document); if (documentDb == null) { throw new NsiNotFoundException(DocumentMessages.DocumentNotFound); } _context.SaveChanges(); return(documentDb.DocumentId); }
public int CreateDocument(DocumentDomain document) { if (document == null) { throw new NsiArgumentException(DocumentMessages.DocumentInvalidArgument); } if (!_context.FileType.Any(x => x.FileTypeId == document.FileTypeId)) { throw new NsiArgumentException(document.toString()); } if (!_context.StorageType.Any(x => x.StorageTypeId == document.StorageTypeId)) { throw new NsiArgumentException(StorageTypeMessages.StorageTypeInvalidId); } var documentDb = new Document().FromDomainModel(document); _context.Document.Add(documentDb); _context.SaveChanges(); return(documentDb.DocumentId); }
public async Task <IHttpActionResult> UploadFile(string fileName = "", string description = "") { //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]; fileName = Path.GetFileNameWithoutExtension(uploadedFile.Headers.ContentDisposition.FileName.Trim('"')); //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 = ""; string[] tokens = extension.Split('.'); string extensionName = tokens[tokens.Length - 1]; var fileTypeId = _fileTypeManipulation.GetFileIdByExtension(extensionName); if (this._azureActive.Equals("true")) { storageConnectionString = ConfigurationManager.AppSettings["azurestoragepath"]; var storageAccount = CloudStorageAccount.Parse(storageConnectionString); var blobClient = storageAccount.CreateCloudBlobClient(); var container = blobClient.GetContainerReference("nsicontainer"); 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 document = new DocumentDomain { DocumentId = 0, Name = fileName, Path = blockBlob.Uri.ToString(), FileSize = blockBlob.StreamWriteSizeInBytes, ExternalId = Guid.NewGuid(), LocationExternalId = blockBlob.Uri.ToString(), DateCreated = DateTime.Now, StorageTypeId = 1, FileTypeId = fileTypeId, Description = description }; var result = _documentManipulation.CreateDocument(document); return(Ok(result)); } else if (this._azureActive.Equals("false")) { var localFilePath = ConfigurationManager.AppSettings["localstoragepath"]; var guid = Guid.NewGuid(); var fullPath = $@"{localFilePath}\{fileName}{extension}"; var fileSize = 0; using (var fileStream = await uploadedFile.ReadAsStreamAsync()) using (var localFileStream = File.Create(fullPath)) { fileStream.Seek(0, SeekOrigin.Begin); fileStream.CopyTo(localFileStream); fileSize = (int)fileStream.Length; } if (!DocumentManipulation.IsSafe(fullPath)) { File.Delete(fullPath); return(BadRequest("File contains malware")); } var document = new DocumentDomain { DocumentId = 0, Name = fileName, Path = fullPath, FileSize = fileSize, ExternalId = guid, LocationExternalId = "", DateCreated = DateTime.Now, StorageTypeId = 2, FileTypeId = fileTypeId, Description = description }; var result = _documentManipulation.CreateDocument(document); return(Ok(result)); } else { return(BadRequest(DocumentMessages.UnexpectedProblem)); } }
public FileAPIHandler() : base() { DocumentDomain documentDomain = new DocumentDomain(new DocumentRepository()); userlog log = new userlog(); Before += ctx => { // new userlogB().Insert(new userlog { }); log.ip = ctx.Request.UserHostAddress; log.loginfo = ctx.Request.Path; log.remark = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); return(ctx.Response); }; Post["/document/checkauth"] = p => { // new DocumentRepository().SaveDocument("3b31d546f6f94a8029f966a8d71c7c66", "SWXX", "123123", ".png", "image/png", @"D:\FileCenter\SWXX\201601\3b31d546f6f94a8029f966a8d71c7c66.png", DateTime.Now); string code = this.Request.Form.code; string secret = this.Request.Form.secret; Qycode space = new QycodeB().GetEntities(d => d.Code == code && d.secret == secret).FirstOrDefault(); return(space == null ? "N" : "Y"); }; Post["/document/fileupload"] = p => { //借助上传组件工具上传 try { string size = this.Request.Form.size; string chunks = this.Request.Form.chunks; string strchunk = this.Request.Form.chunk; string fileMd5 = this.Request.Form.fileMd5; string spacecode = this.Request.Form.code; string upinfo = this.Request.Form.upinfo; if (!string.IsNullOrEmpty(spacecode)) { spacecode = spacecode.Trim('\''); int chunkcount = 0, chunk; if (!string.IsNullOrEmpty(chunks) && int.TryParse(chunks, out chunkcount) && chunkcount > 1 && int.TryParse(strchunk, out chunk)) { //属于分片文件 var file = this.Request.Files.FirstOrDefault(); if (file != null) { var md5 = documentDomain.PushChunk(fileMd5, chunk, file.Name, Path.GetExtension(file.Name), file.ContentType, file.Value); return(Response.AsJson(md5)); } } else { var file = this.Request.Files.FirstOrDefault(); if (file != null) { var md5 = documentDomain.Push(file.Name, System.IO.Path.GetExtension(file.Name), file.ContentType, file.Value, spacecode, upinfo); return(Response.AsJson(md5)); } } } return(Response.AsRedirect("/document")); } catch (Exception ex) { Logger.LogError(ex.Message.ToString()); return(Response.AsRedirect("/document")); } }; Post["/document/fileupload/{qycode}/{upinfo}"] = p => { //后台上传 try { string qycode = p.qycode; string upinfo = p.upinfo; var file = this.Request.Files.FirstOrDefault(); if (file != null) { var md5 = documentDomain.Push(file.Name, System.IO.Path.GetExtension(file.Name), file.ContentType, file.Value, qycode, upinfo); return(Response.AsText(md5)); } return(Response.AsRedirect("/document")); } catch (Exception ex) { Logger.LogError(ex.Message.ToString()); return(Response.AsRedirect("/document")); } }; Post["/document/fileupload/{qycode}"] = p => { //后台上传 try { string qycode = p.qycode; var file = this.Request.Files.FirstOrDefault(); if (file != null) { var md5 = documentDomain.Push(file.Name, System.IO.Path.GetExtension(file.Name), file.ContentType, file.Value, qycode, ""); return(Response.AsText(md5)); } return(Response.AsRedirect("/document")); } catch (Exception ex) { Logger.LogError(ex.Message.ToString()); return(Response.AsRedirect("/document")); } }; Post["/document/fileupload/checkwholefile"] = p => { var md5Client = this.Request.Form.md5; string spacecode = this.Request.Form.code; //MD5值验证 string md5 = md5Client.Value.ToLower(); var result = documentDomain.Exist(spacecode, md5); return(Response.AsJson(result)); }; Post["/document/fileupload/fileMerge"] = p => { string fileMd5 = this.Request.Form.fileMd5; string ext = this.Request.Form.ext; string name = this.Request.Form.name; string contentType = this.Request.Form.contentType; string spacecode = this.Request.Form.code; string upinfo = this.Request.Form.upinfo; if (!ext.StartsWith(".")) { ext = "." + ext; } string strID = "0"; var result = documentDomain.FileMerge(fileMd5, name, contentType, ext, spacecode, upinfo); return(Response.AsJson(result)); }; Get["/{qycode}/document/fileupload"] = p => { string strCode = p.qycode; Qycode space = new QycodeB().GetEntities(d => d.Code == strCode).FirstOrDefault(); return(View["FileUpload"]); }; Get["/document/info/{id}"] = p => { string idS = p.id; string[] ids = idS.Trim(',').Split(','); List <Document> spaces = new DocumentB().GetEntities(d => d.Qycode == "-1").ToList(); foreach (string id in ids) { Document space = new DocumentB().GetEntities(d => d.ID == id).FirstOrDefault(); if (space != null) { spaces.Add(space); } } return(Response.AsJson(spaces)); }; //下一版废弃 Get["/{qycode}/document/{id}"] = p => { log.useraction = "下载文件"; string id = p.id; string qycode = p.qycode; if (!string.IsNullOrEmpty(id) && id.Contains(",")) { var md5s = id.Split(','); var documents = documentDomain.Fetch("", md5s); if (documents != null && documents.Any()) { //压缩,并返回 var mimeType = "application/zip"; var extension = "zip"; var name = "打包下载的文件"; var file = documentDomain.Compress(documents); return(Response.AsFileV1(file, mimeType, extension, name)); } else { return("找不到该文件" + p.id); } } else { var document = documentDomain.Fetch("", p.id); if (document == null) { return("找不到该文件 " + p.id); } string mimeType = document.contenttype; string extension = document.extension; string file = document.file; string name = document.name; return(Response.AsFileV1(file, mimeType, extension, name)); } }; Get["/document/{id}"] = p => { log.useraction = "下载文件"; string id = p.id; if (!string.IsNullOrEmpty(id) && id.Contains(",")) { var md5s = id.Split(','); var documents = documentDomain.Fetch("", md5s); if (documents != null && documents.Any()) { //压缩,并返回 var mimeType = "application/zip"; var extension = "zip"; var name = "打包下载的文件"; var file = documentDomain.Compress(documents); return(Response.AsFileV1(file, mimeType, extension, name)); } else { return("找不到该文件" + p.id); } } else { var document = documentDomain.Fetch("", p.id); if (document == null) { return("找不到该文件 " + p.id); } string mimeType = document.contenttype; string extension = document.extension; string file = document.file; string name = document.name; return(Response.AsFileV1(file, mimeType, extension, name)); } }; Get["/document/zipfile/{md5}"] = p => { string md5 = p.md5; var filename = documentDomain.GetZipFile(md5); var mimeType = "application/zip"; var extension = "zip"; var name = "打包下载的文件"; return(Response.AsFileV1(filename, mimeType, extension, name)); }; Get["/{qycode}/document/image/{id}"] = p => { log.useraction = "预览图片"; string id = p.id; string qycode = p.qycode; var document = documentDomain.Fetch(qycode, p.id); if (document == null) { return("找不到该文件" + p.id); } string mimeType = document.contenttype; string extension = document.extension; string file = document.file; string name = document.name; return(Response.AsPreviewFile(file, mimeType, extension, name)); }; //修改缩略图接口 Get["/{qycode}/document/image/{id}/{width?0}/{height?0}"] = p => { log.useraction = "预览压缩图片"; string id = p.id; string qycode = p.qycode; var document = documentDomain.Fetch(qycode, p.id); if (document == null) { return("找不到该文件 " + p.id); } int width = p.width; int height = p.height; string mimeType = document.contenttype; string extension = document.extension; string file = document.file; string name = document.name; var smallImg = ImageCLass.GenSmallImg(file, width, height); return(Response.AsPreviewFile(smallImg, mimeType, extension, name)); }; Get["/{qycode}/document/unzip/{id}"] = p => { string qycode = p.qycode; var document = documentDomain.Fetch(qycode, p.id); if (document == null) { return("找不到该文档 " + p.id); } string extension = document.extension; if (extension == "zip") { SubFolderModel model = documentDomain.UnCompress(document, p.qycode); return(Response.AsJson(model)); } return(Response.AsJson("")); }; Post["/{qycode}/document/zipfolder"] = p => { var data = Request.Form.data; string qycode = p.qycode; string md5 = ""; if (data) { SubFolderModel subFolderModel = Newtonsoft.Json.JsonConvert.DeserializeObject <SubFolderModel>(data); var zipItems = subFolderModel.GetZipEntryItems().ToArray(); var md5s = zipItems.Select(o => o.Item1).ToArray(); var documents = documentDomain.Fetch(qycode, md5s); if (documents != null && documents.Any()) { md5 = documentDomain.CompressNestedFolder(documents, zipItems); } } return(md5); }; Get["/{qycode}/document/zipfile/{md5}"] = p => { string md5 = p.md5; var filename = documentDomain.GetZipFile(md5); var mimeType = "application/zip"; var extension = "zip"; var name = "打包下载的文件"; return(Response.AsFileV1(filename, mimeType, extension, name)); }; Post["/{qycode}/document/nestedfolder"] = p => { var data = Request.Form.data; string qycode = p.qycode; if (data) { SubFolderModel subFolderModel = Newtonsoft.Json.JsonConvert.DeserializeObject <SubFolderModel>(data); var zipItems = subFolderModel.GetZipEntryItems().ToArray(); var md5s = zipItems.Select(o => o.Item1).ToArray(); var documents = documentDomain.Fetch(qycode, md5s); if (documents != null && documents.Any()) { //压缩,并返回 var mimeType = "application/zip"; var extension = "zip"; var name = subFolderModel.Name; string file = documentDomain.CompressNestedFolder(documents, zipItems); return(Response.AsFileV1(file, mimeType, extension, name)); } else { return("找不到该文档 " + subFolderModel.Name); } } return(""); }; #region 多媒体相关接口 Get["/document/officecov/{id}"] = p => { string strReturn = "0,0"; string id = p.id; Document document = documentDomain.Fetch(p.id); if (document == null) { return("找不到该文件" + p.id); } else { strReturn = document.isyl + "," + document.ylinfo; if (document.isyl == "0") { string extension = document.Extension.TrimStart('.'); string file = document.FullPath; //OfficeConverter Converter = new OfficeConverter(); //if (new List<string>() { "pdf" }.Contains(extension.ToLower())) //{ // Converter.PdfToImage(file, file.Substring(0, file.LastIndexOf('.')), 0, 0, 400); //} //if (new List<string>() { "doc", "docx" }.Contains(extension.ToLower())) //{ // Converter.WordToImage(document, file.Substring(0, file.LastIndexOf('.')), 0, 0, null, 400); //} //if (new List<string>() { "ppt", "pptx" }.Contains(extension.ToLower())) //{ // Converter.PPTToImage(file, file.Substring(0, file.LastIndexOf('.')), 0, 0, 400); //} } //if (new List<string>() { "xls", "xlsx" }.Contains(extension.ToLower())) //{ // strReturn = Converter.YLExcel(file); // return Response.AsRedirect(strReturn); //} return(strReturn); } }; //返回office预览文件 Get["/document/YL/{id}"] = p => { log.useraction = "预览OFFICE文件"; Document document = documentDomain.Fetch(p.id); if (document == null) { return("找不到可预览的文件 " + p.id); } else if (document.isyl != "2") { return("预览文件正在准备中 " + p.id); } else { string strFileName = document.FileName.Substring(0, document.FileName.LastIndexOf('.')); string strReturn = "/Web/Html/doc.html?ID=" + p.id + "&size=" + document.ylinfo + "&title=" + HttpUtility.UrlEncode(strFileName); return(Response.AsRedirect(strReturn)); } }; //获取可用的视频播放路径 Get["/document/viedo/{id}"] = p => { Document document = documentDomain.Fetch(p.id); string tempfile = document.Directory.TrimEnd('\\') + "\\" + document.Md5 + "\\" + document.Md5; if (document == null) { return("找不到文件 " + p.id); } if (document.isyl != "2") { return("正在生成可预览文件 "); } else { string mimeType = "video/mp4"; string extension = ".mp4"; string file = tempfile + "_low.mp4"; string name = file; string[] range_info = (string[])Request.Headers["Range"]; if (range_info.Length == 0) { return(Response.AsFileV1(file, mimeType, extension, document.ID.ToString() + "_low.mp4")); } else { string strRange = range_info[0].ToString(); return(Response.AsVideoFile(document.FullPath, mimeType, extension, name, strRange)); } } }; //获取视频封面 Get["/document/viedo/img/{id}"] = p => { Document document = documentDomain.Fetch(p.id); string tempfile = document.Directory.TrimEnd('\\') + "\\" + document.Md5 + "\\" + document.Md5; if (document == null) { return("找不到文件 " + p.id); } if (document.isyl != "2") { return("正在生成可预览文件 "); } else { string mimeType = "image/jpeg"; string extension = ".jpg"; string file = tempfile + ".jpg"; string name = file; return(Response.AsPreviewFile(file, mimeType, extension, name)); } }; //获取office转换后的图片 Get["/document/YL/{id}/{index}"] = p => { log.useraction = "预览OFFICE图片"; string strReturn = "无法预览"; string id = p.id; string index = p.index; Document document = documentDomain.Fetch(p.id); if (document == null) { return("找不到可预览的文件 " + p.id); } else { if (document.isyl == "1") { strReturn = "预览准备中"; } if (document.isyl == "2") { string ylfile = document.FullPath; ylfile = ylfile.Substring(0, ylfile.LastIndexOf('.')) + "/" + document.Md5 + "_" + index + ".png"; string strName = document.Md5 + "_" + index + ".png"; if (new List <string>() { ".ppt", ".pptx", ".doc", ".docx", ".pdf" }.Contains(document.Extension.ToLower())) { if (File.Exists(ylfile)) { return(Response.AsPreviewFile(ylfile, "image/png", ".png", strName)); } } } } return(strReturn); }; After += ctx => { //添加日志 new userlogB().Insert(log); }; #endregion }