public async Task <UploadResponseDto> ApplicationCaseDocumentPut(UploadDto model)
        {
            try
            {
                var project = await _applicationCaseRepository.GetAsync(model.Id);


                string documentName = null;
                if (model.Document != null)
                {
                    documentName = await CommonFileStringDocumentUpload(model.Document);

                    if (!project.FileKey.IsNullOrEmpty())
                    {
                        //字段中默认只放一个文档所以要删除掉之前的
                        var sign = project.FileKey.Replace(";", "");
                        CommonFileStringDocumentDelete(sign);
                    }
                    project.FileKey = documentName;
                }
                UploadResponseDto uploadResponseDto = new UploadResponseDto
                {
                    Id = "101"
                };
                return(uploadResponseDto);
            }


            catch (Exception ex)
            {
                return(null);
            }
        }
        public async Task <UploadResponseDto> ApplicationCaseDocumentDelete(UploadDto model)
        {
            try
            {
                var project = await _applicationCaseRepository.GetAsync(model.Id);

                if (model.FileKey != null)
                {
                    var sign = CommonFileStringDocumentDelete(model.FileKey);

                    //project.FileKey = project.FileKey.Replace(model.FileKey + ";", "");
                    project.FileKey = null;
                }
                UploadResponseDto uploadResponseDto = new UploadResponseDto
                {
                    Id = "101"
                };
                return(uploadResponseDto);
            }


            catch (Exception ex)
            {
                return(null);
            }
        }
        public async Task <UploadResponseDto> ApplicationCasePicturePut(UploadDto model)
        {
            try
            {
                var project = await _applicationCaseRepository.GetAsync(model.Id);

                string pictureName = null;
                if (model.Photo != null)
                {
                    pictureName = await CommonFileStringUpload(model.Photo);

                    project.FileString += pictureName;
                }


                UploadResponseDto uploadResponseDto = new UploadResponseDto
                {
                    Id = "101"
                };
                return(uploadResponseDto);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Ejemplo n.º 4
0
        public async Task <UploadDto> UploadFile(string fileName, string contentType, Stream stream)
        {
            // CloudConfigurationManager.
            var account   = CloudStorageAccount.Parse(settings.AzureblobStorageConnectionString);
            var client    = account.CreateCloudBlobClient();
            var container = client.GetContainerReference(UploadContainer);

            // Randomize the filename everytime so we don't overwrite files
            string randomFile = Path.GetFileNameWithoutExtension(fileName) +
                                "_" +
                                Guid.NewGuid().ToString().Substring(0, 4) + Path.GetExtension(fileName);

            await container.CreateIfNotExistsAsync(BlobContainerPublicAccessType.Blob, new BlobRequestOptions(), new OperationContext());



            CloudBlockBlob blockBlob = container.GetBlockBlobReference(randomFile);

            blockBlob.Properties.ContentType = contentType;

            await blockBlob.UploadFromStreamAsync(stream);

            //  await Task.Factory.FromAsync((cb, state) => blockBlob.UploadFromStreamAsync(stream, cb, state), ar => blockBlob.EndUploadFromStream(ar), null);

            var result = new UploadDto
            {
                FileName = fileName,
                Url      = blockBlob.Uri.ToString(),
            };

            return(result);
        }
Ejemplo n.º 5
0
        public async Task <UploadDto> UploadFile(string fileName, string contentType, Stream stream)
        {
            var uploadDirectoryPath = Path.Combine(hostingEnvironment.WebRootPath, settings.LocalFileSystemStoragePath);

            string randomFile = Path.GetFileNameWithoutExtension(fileName) +
                                "_" +
                                Guid.NewGuid().ToString().Substring(0, 4) + Path.GetExtension(fileName);


            if (!Directory.Exists(uploadDirectoryPath))
            {
                Directory.CreateDirectory(uploadDirectoryPath);
            }


            var targetFile = Path.GetFullPath(Path.Combine(uploadDirectoryPath, randomFile));

            using (var destinationStream = File.Create(targetFile))
            {
                await stream.CopyToAsync(destinationStream);
            }


            var result = new UploadDto
            {
                FileExtn = Path.GetExtension(fileName),
                FileName = fileName,
                Url      = GetFullUrl(settings.LocalFileSystemStorageUriPrefix, randomFile)
            };

            return(result);
        }
Ejemplo n.º 6
0
        public IActionResult Upload(UploadDto model)
        {
            int kullaniciId = HttpContext.Session.GetInt32("kullaniciid").Value;

            var filePath = _env.WebRootPath + "//files//";

            if (model.file.Length > 0)
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                using (var stream = new FileStream(filePath + model.file.FileName, FileMode.Create))
                {
                    model.file.CopyTo(stream);
                    _kullaniciDokumanService.Insert(new Dokuman
                    {
                        Olusturankisi   = kullaniciId,
                        Guncelleyenkisi = model.etkinlikid,
                        DokumanData     = filePath,
                        Tip             = model.file.ContentType,
                        Ad    = model.file.FileName,
                        Boyut = model.file.Length
                    });
                }
            }

            return(Redirect("/Activity/Files/" + model.etkinlikid));
        }
Ejemplo n.º 7
0
        public async Task <ModelResult> Run([ActivityTrigger] UploadDto uploadDto, ILogger log)
        {
            log.LogInformation("Upload function started.");

            var container = new BlobContainerClient(_options.StorageConnectionString, _options.ContainerName);

            await container.CreateIfNotExistsAsync();

            var fileName = $"{uploadDto.FileName}.pdf";

            var blob = container.GetBlobClient(fileName);

            using (var document = new Document())
            {
                var page = document.Pages.Add();

                page.Paragraphs.Add(new TextFragment(uploadDto.SourceText));

                await using var pdfMs = new MemoryStream();
                document.Save(pdfMs);
                await blob.UploadAsync(pdfMs);
            }

            log.LogInformation(fileName);

            return(new ModelResult("File created", fileName));
        }
        public async Task <UploadResponseDto> MaterialDocumentPut(UploadDto model)
        {
            try
            {
                var project = await _materialRepository.GetAsync(model.Id);

                string documentName = null;
                if (model.Document != null)
                {
                    documentName = await CommonFileStringDocumentUpload(model.Document);

                    project.FileKey += documentName;
                }


                UploadResponseDto uploadResponseDto = new UploadResponseDto
                {
                    Id = "101"
                };
                return(uploadResponseDto);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        public async Task <UploadResponseDto> MaterialPictureDelete(UploadDto model)
        {
            try
            {
                var project = await _materialRepository.GetAsync(model.Id);

                //两表之间没有键之间的关联,通过这种方式改变图片字段存储
                var project1 = _materialRecommendationRepository
                               .Where(t => t.MaterialId == model.Id)
                               .FirstOrDefault();

                if (model.FileString != null)
                {
                    var sign = CommonFileStringDelete(model.FileString);

                    project.FileString = project.FileString.Replace(model.FileString + ";", "");
                }
                project1.FileString = project.FileString;
                UploadResponseDto uploadResponseDto = new UploadResponseDto
                {
                    Id = "101"
                };
                return(uploadResponseDto);
            }


            catch (Exception)
            {
                return(null);
            }
        }
Ejemplo n.º 10
0
        public async Task Store(UploadDto dto)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                await dto.File.CopyToAsync(ms);

                byte[] fileContent = ms.ToArray();
                await fileStorage.Store(dto.File.FileName, fileContent, dto.IsOvewrite);
            }
        }
Ejemplo n.º 11
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Upload([FromForm] UploadDto uploadDto)
        {
            if (ModelState.IsValid)
            {
                if (!Validate(uploadDto.File))
                {
                    return(BadRequest("Validation failed!"));
                }

                var fileName   = DateTime.Now.ToString("yyyymmddMMss") + "_" + Path.GetFileName(uploadDto.File.FileName);
                var folderPath = Path.Combine(_environment.WebRootPath, "uploads");
                var filePath   = Path.Combine(folderPath, fileName);
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await uploadDto.File.CopyToAsync(fileStream);
                }

                var user = _context.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);
                var room = _context.Rooms.FirstOrDefault(r => r.Id == uploadDto.RoomId);
                if (user == null || room == null)
                {
                    return(NotFound());
                }

                var htmlImage = string.Format(
                    "<a href=\"/uploads/{0}\" target=\"_blank\">" +
                    "<img src=\"/uploads/{0}\" class=\"post-image\">" +
                    "</a>", fileName);

                var message = new Message
                {
                    Content   = Regex.Replace(htmlImage, @"(?i)<(?!img|a|/a|/img).*?>", string.Empty),
                    Timestamp = DateTime.Now,
                    FromUser  = user,
                    ToRoom    = room
                };

                await _context.Messages.AddAsync(message);

                await _context.SaveChangesAsync();

                // Send image-message to group
                var messageDto = _mapper.Map <Message, MessageDto>(message);
                await _hubContext.Clients.Group(room.Name).SendAsync("newMessage", messageDto);

                return(Ok());
            }

            return(BadRequest());
        }
        public async Task <IActionResult> Upload([FromForm] UploadDto inputDto)
        {
            try
            {
                await this.fileUploadService.Store(inputDto);

                return(this.Ok());
            }
            catch (Exception ex)
            {
                return(this.BadRequest());
            }
        }
Ejemplo n.º 13
0
        public async Task <int> SaveUpload(UploadDto uploadDto)
        {
            var q =
                @"INSERT INTO [dbo].[Upload](Filename,Type,Url,CreatedDate,CreatedById,ParentId) VALUES(@fileName,@Type,@Url,@CreatedDate,@CreatedById,@ParentId);SELECT CAST(SCOPE_IDENTITY() as int)";

            using (var con = new SqlConnection(ConnectionString))
            {
                con.Open();
                var ss = await con.QueryAsync <int>(q, uploadDto);

                return(ss.Single());
            }
        }
        public void Execute(UploadDto request)
        {
            _validator.ValidateAndThrow(request);

            var guid      = Guid.NewGuid();
            var extension = Path.GetExtension(request.Image.FileName);

            var newFileName = guid + extension;
            var path        = Path.Combine("wwwroot", "images", newFileName);

            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                request.Image.CopyTo(fileStream);
            }
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> UploadNewVersion([FromForm] UploadDto uploadDto)
        {
            if (uploadDto.File.Length > 0)
            {
                var fileData = new FileData()
                {
                    Created   = DateTime.Now,
                    Extension = Path.GetExtension(uploadDto.File.FileName),
                    Name      = uploadDto.File.FileName.Replace(Path.GetExtension(uploadDto.File.FileName), ""),
                };

                using (var ms = new MemoryStream())
                {
                    uploadDto.File.CopyTo(ms);
                    var fileBytes = ms.ToArray();

                    fileData.Content = fileBytes;
                }

                await _repo.UploadFile(fileData);

                if (fileData.Id > 0)
                {
                    var newVersion = new Database.Entities.Version
                    {
                        Created     = DateTime.Now,
                        Major       = uploadDto.Major.Value,
                        Minor       = uploadDto.Minor.Value,
                        Patch       = uploadDto.Patch.Value,
                        Name        = uploadDto.Name ?? fileData.Name,
                        FileDataId  = fileData.Id,
                        ComponentId = uploadDto.ComponentId,
                        KindId      = uploadDto.KindId
                    };

                    await _repo.AddVersion(newVersion);

                    if (newVersion.Id > 0)
                    {
                        return(StatusCode((int)HttpStatusCode.Created));
                    }
                }
            }

            return(StatusCode((int)HttpStatusCode.InternalServerError, "Error Upload"));
        }
Ejemplo n.º 16
0
        public IActionResult Post([FromForm] UploadDto dto)
        {
            var guid      = Guid.NewGuid();
            var extension = Path.GetExtension(dto.Image.FileName);

            var newFileName = guid + extension;

            var path = Path.Combine("wwwroot", "images", newFileName);

            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                dto.Image.CopyTo(fileStream);
            }

            return(Created("201", new {
                imageName = newFileName
            }));
        }
Ejemplo n.º 17
0
 public Result Add(UploadDto dto)
 {
     try
     {
         var up  = dto.MapTo <UploadEntity>();
         var rlt = UnitOfWorkService.Execute(() => _uploadRepository.InsertAndGetId(up));
         return(rlt > 0 ? new Result(true, "") : new Result {
             Status = false
         });
     }
     catch (Exception ex)
     {
         Logger.Error($" add upload to exception:{ex}");
         return(new Result {
             Status = false, Message = ex.Message
         });
     }
 }
Ejemplo n.º 18
0
        public async Task <IActionResult> UpdateVersion(int id, UploadDto uploadDto)
        {
            var version = await _repo.Find <Database.Entities.Version>(id);

            if (version == null)
            {
                return(BadRequest());
            }

            if (!string.IsNullOrEmpty(uploadDto.Name))
            {
                version.Name = uploadDto.Name;
            }

            if (uploadDto.Major.HasValue)
            {
                version.Major = uploadDto.Major.Value;
            }

            if (uploadDto.Minor.HasValue)
            {
                version.Minor = uploadDto.Minor.Value;
            }

            if (uploadDto.Patch.HasValue)
            {
                version.Patch = uploadDto.Patch.Value;
            }

            if (uploadDto.ComponentId.HasValueGreaterThan(0))
            {
                version.ComponentId = uploadDto.ComponentId.Value;
            }

            if (uploadDto.KindId.HasValueGreaterThan(0))
            {
                version.KindId = uploadDto.KindId.Value;
            }

            await _repo.SaveAllChangesAsync();

            return(Ok());
        }
Ejemplo n.º 19
0
        public async Task <Upload> AddAsync(UploadDto dto, CancellationToken token = default)
        {
            using (var db = new GuoGuoCommunityContext())
            {
                var entity = db.Uploads.Add(new Upload
                {
                    Agreement             = dto.Agreement,
                    Directory             = dto.Directory,
                    Domain                = dto.Domain,
                    File                  = dto.File,
                    Host                  = dto.Host,
                    CreateOperationTime   = dto.OperationTime,
                    CreateOperationUserId = dto.OperationUserId,
                    LastOperationTime     = dto.OperationTime,
                    LastOperationUserId   = dto.OperationUserId
                });
                await db.SaveChangesAsync(token);

                return(entity);
            }
        }
Ejemplo n.º 20
0
        public void Post([FromForm] UploadDto dto)
        {
            var guid        = Guid.NewGuid();
            var extension   = Path.GetExtension(dto.Image.FileName);
            var newFileName = guid + extension;

            var path = Path.Combine("wwwroot", "productImages", newFileName);

            using (var fileStrem = new FileStream(path, FileMode.Create))
            {
                dto.Image.CopyTo(fileStrem);
            }
            var pic = new ProductPic
            {
                src       = path,
                alt       = newFileName,
                ProductId = (int)dto.ProductId
            };

            _context.ProductPics.Add(pic);
            _context.SaveChanges();
        }
        public async Task <UploadResponseDto> MaterialPicturePut(UploadDto model)
        {
            try
            {
                var project = await _materialRepository.GetAsync(model.Id);

                //两表之间没有键之间的关联,通过这种方式改变图片字段存储
                var project1 = _materialRecommendationRepository
                               .Where(t => t.MaterialId == model.Id)
                               .FirstOrDefault();

                string documentName = null;
                if (model.Photo != null)
                {
                    //材料表图片字段只保留一张图片,所以要删掉之前的
                    if (!project.FileString.IsNullOrEmpty())
                    {
                        var sign = CommonFileStringDelete(project.FileString.Replace(";", "").Trim());
                    }
                    documentName = await CommonFileStringUpload(model.Photo);

                    project.FileString = documentName;
                }
                project1.FileString = project.FileString;
                UploadResponseDto uploadResponseDto = new UploadResponseDto
                {
                    Id = "101"
                };
                return(uploadResponseDto);
            }


            catch (Exception)
            {
                return(null);
            }
        }
Ejemplo n.º 22
0
        public Result Upload(UploadDto dto, List <IFormFile> formFiles)
        {
            try
            {
                var files = Request.Form.Files;
                if (files.Count > 0)
                {
                    var file            = files[0];
                    var webRootPath     = _hostingEnvironment.WebRootPath;
                    var contentRootPath = _hostingEnvironment.ContentRootPath;
                    var filePath        = webRootPath + @"/upload/" + file.FileName;
                    using (var stream = System.IO.File.Create(filePath))
                    {
                        file.CopyTo(stream);
                        stream.Flush();
                    }

                    dto.Route    = filePath;
                    dto.Name     = Path.GetFileNameWithoutExtension(filePath);
                    dto.FileName = Path.GetExtension(file.FileName);
                }
                var result = _uploadService.Add(dto);
                if (result.Status)
                {
                    result.Message = "/Upload/Index";
                }
                return(result);
            }
            catch (Exception ex)
            {
                Logger.Error($"错误描述,{ex}");
                return(new Result {
                    Status = false
                });
            }
        }
Ejemplo n.º 23
0
 public async Task <IActionResult> ChangedAvatar(UploadDto img)
 {
     return(Ok(await _userService.ChangeAvatar(img.UserID, img.Imagebase64)));
 }
Ejemplo n.º 24
0
        public IEnumerable <UploadItemResult> Post([FromForm] UploadDto dto)
        {
            var user = HttpContext.GetLoginUserFromToken();

            if (string.IsNullOrWhiteSpace(dto.BusinessType))
            {
                throw new("BusinessType can not be null");
            }
            if (dto.File is null || dto.File.Count == 0)
            {
                throw new("no files find");
            }
            var rsList = new List <UploadItemResult> {
            };

            if (!string.IsNullOrWhiteSpace(dto.DeleteIds))
            {
                var delete_ids = dto.DeleteIds.Split(',', '|', ';');
                foreach (var did in delete_ids)
                {
                    bucket.Delete(ObjectId.Parse(did));
                }
            }
            foreach (var item in dto.File)
            {
                if (item.ContentType is null)
                {
                    throw new Exception("ContentType in File is null");
                }
                var uploadOptions = new GridFSUploadOptions
                {
                    BatchSize = dto.File.Count,
                    Metadata  = new()
                    {
                        { "contentType", item.ContentType }
                    }
                };
                var bapp = dto.App ?? GridFSUploadBuildExtensions.BusinessApp;
                if (string.IsNullOrWhiteSpace(bapp))
                {
                    throw new("BusinessApp can not be null");
                }
                _ = uploadOptions.Metadata.AddRange(new BsonDocument {
                    { "app", bapp }
                });
                if (!string.IsNullOrWhiteSpace(dto.BusinessType))
                {
                    _ = uploadOptions.Metadata.AddRange(new BsonDocument {
                        { "business", dto.BusinessType }
                    });
                }
                if (!string.IsNullOrWhiteSpace(dto.Category))
                {
                    _ = uploadOptions.Metadata.AddRange(new BsonDocument {
                        { "category", dto.Category }
                    });
                }
                _ = uploadOptions.Metadata.AddRange(new BsonDocument {
                    { "creator", user.ToOperator().ToBsonDocument() }
                });
                var oid = bucket.UploadFromStream(item.FileName, item.OpenReadStream(), uploadOptions);
                rsList.Add(new()
                {
                    FileId      = oid.ToString(),
                    FileName    = item.FileName,
                    Length      = item.Length,
                    ContentType = item.ContentType
                });
            }
            return(rsList);
        }
Ejemplo n.º 25
0
 public async Task <int> SaveUpload(UploadDto uploadDto)
 {
     uploadDto.CreatedDate = DateTime.UtcNow;
     return(await uploadRepository.SaveUpload(uploadDto));
 }
Ejemplo n.º 26
0
        /// <summary>
        /// (multi rows)save multi upload files, & update db(DB save file related path !!)
        /// multi files no need to delete file !!
        /// </summary>
        /// <param name="rows">rows for update db</param>
        /// <param name="files">uploaf files array</param>
        /// <param name="path">save file model</param>
        /// <param name="fileTail">file tail to save</param>
        /// //<param name="kid">pkey field id, if pkey value is empty, will write "_" + key value</param>
        /// <param name="fileFid">column id for save file path</param>
        /// <returns></returns>
        public static async Task SetRowsFilesAsync(JArray rows, List <IFormFile> files, UploadDto path, string fileTail, string fileFid)
        {
            //check input
            if (files == null || files.Count == 0 || rows == null || rows.Count == 0)
            {
                return;
            }

            //get path
            var saveDir    = _Str.AddAntiSlash(path.SaveDir);
            var serverPath = (path.ServerPath == "") ? AppDomain.CurrentDomain.BaseDirectory : path.ServerPath;

            serverPath = _Str.AddAntiSlash(serverPath);

            //var key = "";   //pkey value
            foreach (JObject row in rows)
            {
                var fileNo = Convert.ToInt32(row["_fileNo"]);
                if (fileNo < 0)
                {
                    continue;
                }

                var file = files[fileNo];

                //save file
                //var filePath = saveDir + fileTail + key + Path.GetExtension(file.FileName);
                //var filePath = GetFilePath(saveDir, fileTail + key, file);
                var filePath = GetFilePath(saveDir, fileTail, file);
                //file.SaveAs(serverPath + "\\" + filePath);
                await SaveFileAsync(file, filePath);

                //change field value of uploadf file(save related path)
                row[fileFid] = path.PreUrl + filePath.Replace("\\", "/");
            }
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            //These samples refer to the RESTful interfaces of the d.ecs apps DMSApp and IdentityProviderApp which
            //are contained in d.3one. Cloud and on-premises instances can be used both.

            //First of all: These samples uses current api versions. Please use the d.velop cloud or download current
            //versions for on-premises instances.

            //Follow the steps in this online tutorial before running the code: https://developer.d-velop.de/dev/en/tutorials/dms-api-erste-schritte-zur-anbindung-eines-externen-systems-an-die-dms-app


            //ONE: get these values from your d.3one instance:

            //base uri of your d.3one instance.
            var baseURI = @"https://xxxxxxxxxx.d-velop.cloud";

            //api key for your user in your d.3one instance. Check the users permissions for the desired document types.
            var apiKey = @"xxxxxxxxxxxxxxxxxxxxxx";

            //repository id from your d.3one instance
            var repoId = @"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";


            //TWO: copy sample files from project folder "sample files" to local directory and set filePath to this directory

            //upload file and download path
            var filePath         = Path.Combine(Path.GetTempPath(), "DMSAPISamples");
            var uploadFileName   = "upload.pdf";
            var uploadFile       = Path.Combine(filePath, uploadFileName);
            var downloadFilePath = Path.Combine(filePath, "download");

            var uploadDto = new UploadDto();

            uploadDto.filename = uploadFileName;


            //THREE: get these values from your source system:

            //source id of the choosen source system
            uploadDto.sourceId = @"xxxxx\xxxxx\xx";

            uploadDto.sourceCategory = @"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

            //source keys for document properties
            var sourceKeyFilename = "property_filename";

            uploadDto.sourceProperties.properties.Add(new PropertyDto("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Hello world!"));    //Betreff
            uploadDto.sourceProperties.properties.Add(new PropertyDto("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "4711"));            //Kundennummer
            uploadDto.sourceProperties.properties.Add(new PropertyDto("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "ForYou Möbel AG")); //Kundenname
            uploadDto.sourceProperties.properties.Add(new PropertyDto("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "2018-03-11"));      //Belegdatum


            //FOUR: run this code.

            //url parameters for search sample
            var searchFor = "?sourceid=" + uploadDto.sourceId + "&sourcecategories=[\"schriftverkehrkunde\"]&sourceproperties={\"belegdatum\":[\"2018-03-11\"]}";

            //Important: Tls 1.0 is no longer supported! Please use the next line of code for compatibilty settings or
            //select the most recent .NET Framework for this project!
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            //using apiKey authentication is recommended!
            //for all further api calls use the returned sessionId as Bearer-Token!
            var sessionId = Authenticate(baseURI, apiKey);

            if (null != sessionId)
            {
                //upload file as a whole or chunked
                var documentLink = UploadFile(baseURI, sessionId, repoId, uploadFile, uploadDto).Result;
                //show uploaded document in d.3one
                System.Diagnostics.Process.Start(baseURI + documentLink);
                //get download url and document properties (returned properties are defined in the source mapping, see above)
                var documentInfo = GetDocumentInfo(baseURI, sessionId, repoId, documentLink).Result;
                //download document
                bool downloaded = DownloadDocument(baseURI, sessionId, repoId, documentInfo, downloadFilePath, sourceKeyFilename).Result;
                //search documents
                var result = SearchDocument(baseURI, sessionId, repoId, searchFor).Result;
            }
            Console.ReadKey();
        }
Ejemplo n.º 28
0
        private static async Task <string> FinishFileUpload(string baseURI, string sessionId, string repoId, string contentLocationUri, string filePath, UploadDto uploadDto)
        {
            var link_relation = "/dms/r/" + repoId + "/o2m";
            var baseRequest   = baseURI + link_relation;

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new System.Uri(baseURI);
                client.DefaultRequestHeaders.Add("Origin", baseURI);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sessionId);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MEDIA_TYPE_HAL_JSON));

                //read mapping and replace content location uri
                uploadDto.contentLocationUri = contentLocationUri;
                string output = JsonConvert.SerializeObject(uploadDto);

                StringContent data = new StringContent(output);
                data.Headers.ContentType = new MediaTypeWithQualityHeaderValue(MEDIA_TYPE_HAL_JSON);

                var result = await client.PostAsync(link_relation, data).ConfigureAwait(false);

                if (result.IsSuccessStatusCode)
                {
                    Console.WriteLine("upload ok: " + baseRequest);
                    return(result.Headers.Location.ToString());
                }
                else
                {
                    Console.WriteLine("upload failed: " + baseRequest);
                    return(String.Empty);
                }
            }
        }
Ejemplo n.º 29
0
        //upload file in chunks
        private async static Task <string> UploadFileChunked(string baseURI, string sessionId, string repoId, string filePath, UploadDto uploadDto)
        {
            var path = Path.GetDirectoryName(filePath);
            var name = Path.GetFileNameWithoutExtension(filePath);
            var contentLocationUri = "/dms/r/" + repoId + "/blob/chunk";
            var index         = 0;
            var chunkFilePath = Path.Combine(path, name + index);

            //first: upload file and get an URI (contentLocationUri) as a reference to this file
            while (File.Exists(chunkFilePath))
            {
                contentLocationUri = await UploadFileChunk(baseURI, sessionId, contentLocationUri, chunkFilePath).ConfigureAwait(false);;
                chunkFilePath      = Path.Combine(path, name + ++index);
            }

            //second: upload metadata with reference URI (contentLocationUri).
            var documentLink = await FinishFileUpload(baseURI, sessionId, repoId, contentLocationUri, filePath, uploadDto).ConfigureAwait(false);;

            if (null != documentLink)
            {
                return(documentLink);
            }
            return(string.Empty);
        }
Ejemplo n.º 30
0
        //upload file in a whole
        private async static Task <string> UploadFile(string baseURI, string sessionId, string repoId, string filePath, UploadDto uploadDto)
        {
            var contentLocationUri = "/dms/r/" + repoId + "/blob/chunk";

            //first: upload file and get an URI (contentLocationUri) as a reference to this file
            contentLocationUri = await UploadFileChunk(baseURI, sessionId, contentLocationUri, filePath).ConfigureAwait(false);;

            //second: upload metadata with reference URI (contentLocationUri).
            var documentLink = await FinishFileUpload(baseURI, sessionId, repoId, contentLocationUri, filePath, uploadDto).ConfigureAwait(false);;

            if (null != documentLink)
            {
                return(documentLink);
            }
            return(string.Empty);
        }