public HttpResponseMessage UploadDocument(int documentTypeId, int entityId, string documentName = null) { try { // Ensure a file was uploaded. var files = HttpContext.Current.Request.Files; var uploadedFile = files.AllKeys.Select(fk => files[fk]).FirstOrDefault(); if (uploadedFile == null) { GenerateResponse(HttpStatusCode.BadRequest, "No file was sent."); } var rockContext = new RockContext(); // Ensure the caller is authorized to save a document of the specified type. var documentType = new DocumentTypeService(rockContext) .Queryable("BinaryFileType") .AsNoTracking() .Where(dt => dt.Id == documentTypeId) .FirstOrDefault(); if (documentType == null) { GenerateResponse(HttpStatusCode.InternalServerError, "Invalid document type."); } if (!documentType.IsAuthorized(Rock.Security.Authorization.EDIT, GetPerson())) { GenerateResponse(HttpStatusCode.Unauthorized, "Not authorized to upload this type of document."); } // Ensure the caller is authorized to save a binary file of the specified type. if (documentType.BinaryFileType == null) { GenerateResponse(HttpStatusCode.InternalServerError, "Invalid binary file type."); } if (!documentType.BinaryFileType.IsAuthorized(Rock.Security.Authorization.EDIT, GetPerson())) { GenerateResponse(HttpStatusCode.Unauthorized, "Not authorized to upload this type of file."); } string fileName = Path.GetFileName(uploadedFile.FileName); // Create the binary file. var binaryFile = new BinaryFile { BinaryFileTypeId = documentType.BinaryFileTypeId, MimeType = uploadedFile.ContentType, FileName = fileName, FileSize = uploadedFile.ContentLength, ContentStream = FileUtilities.GetFileContentStream(uploadedFile) }; new BinaryFileService(rockContext).Add(binaryFile); // Create the document, linking the entity and binary file. var document = new Document { DocumentTypeId = documentTypeId, EntityId = entityId, Name = !string.IsNullOrWhiteSpace(documentName) ? documentName : fileName, BinaryFile = binaryFile }; new DocumentService(rockContext).Add(document); // Save the object graph. rockContext.SaveChanges(); // Return the ID of the newly-saved document. return(new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(document.Id.ToString()) }); } catch (HttpResponseException exception) { return(exception.Response); } catch { return(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Unhandled exception") }); } }