コード例 #1
0
        public async Task <DownloadFileModel> DownloadFileAsync(string objectName, CancellationToken ct = default(CancellationToken))
        {
            try {
                var client   = CreateClient();
                var statTask = client.StatObjectAsync(_bucketName, objectName, cancellationToken: ct);
                var fm       = new DownloadFileModel();
                using (var ms = new MemoryStream()) {
                    await client.GetObjectAsync(_bucketName, objectName, s => {
                        // ReSharper disable once AccessToDisposedClosure
                        s.CopyTo(ms);
                    }, cancellationToken : ct);

                    fm.Content = ms.ToArray();
                }

                var stat = await statTask;
                fm.ContentType = stat.ContentType;
                fm.ObjectName  = stat.ObjectName;
                fm.Etag        = stat.ETag;
                return(fm);
            }
            catch (BucketNotFoundException) {
                return(null);
            }
            catch (ObjectNotFoundException) {
                return(null);
            }
        }
コード例 #2
0
        public DownloadFileModel CreateTemplateDownload(EducationSecurityPrincipal user, string templatePath, int serviceOfferingId)
        {
            var offering = ServiceOfferingRepository.Items.Include(s => s.Provider).
                           Include(s => s.ServiceType).
                           Include(s => s.Program).
                           SingleOrDefault(s => s.Id == serviceOfferingId);

            if (offering == null)
            {
                return(null);
            }
            if (!GrantUserAccessToUploadOffering(user, offering))
            {
                throw new EntityAccessUnauthorizedException("You are not have the appropriate rights to download this service offering.");
            }
            var processor    = new WorksheetWriter(offering, ServiceOfferingSheetName);
            var fileName     = string.Format(CultureInfo.InvariantCulture, "{0}{1}", offering.Name.GetSafeFileName(), ".xlsx");
            var downloadFile = new DownloadFileModel
            {
                FileName    = fileName,
                BlobAddress = string.Empty
            };
            ExcelWriter writer = new ExcelWriter();

            writer.InitializeFrom(templatePath, processor);
            downloadFile.FileContentStream          = writer.FileContentStream;
            downloadFile.FileContentStream.Position = 0;
            return(downloadFile);
        }
コード例 #3
0
        public async Task CreateFile(DownloadFileModel file, byte[] contents)
        {
            if ((await _downloadTable.SelectById(file.DownloadId)).Any())
            {
                await _downloadFileTable.Insert(file);

                await _downloadFileApi.Post(file, contents);
            }
        }
コード例 #4
0
        public FileResult GetFile([FromQuery(Name = "messageId")] int msgId)
        {
            DownloadFileModel file = new DownloadFileModel();

            file = messageRep.GetMessageFile(msgId);

            _logger.LogInformation("Message file with id " + msgId.ToString() + " downloaded ");
            return(File(file.ByteArray, "file" + "/" + file.FileName.Substring(file.FileName.IndexOf(".") + 1), file.FileName));
        }
コード例 #5
0
        public async Task DeleteFile(DownloadFileModel file)
        {
            if ((await _downloadTable.SelectById(file.DownloadId)).Any())
            {
                if ((await _downloadFileTable.Select(file.DownloadId)).Where(f => f.Filename == file.Filename).Any())
                {
                    await _downloadFileTable.DeleteByFile(file);

                    await _downloadFileApi.Delete(file.DownloadId, file.Filename);
                }
            }
        }
コード例 #6
0
        protected override void beforeEach()
        {
            _output = new DownloadFileModel
            {
                ContentType   = "image/jpeg",
                LocalFileName = "filename.jpg"
            };

            MockFor <IFubuRequest>().Expect(x => x.Get <DownloadFileModel>()).Return(_output);

            ClassUnderTest.Invoke();
        }
コード例 #7
0
        public DownloadFileModel RetrieveUploadErrorsFile(string blobAddress)
        {
            var memoryStream = new MemoryStream();
            var downloadFile = new DownloadFileModel
            {
                FileName          = blobAddress,
                FileContentStream = memoryStream
            };

            DataFileBlobContainer.DownloadToStream(blobAddress, memoryStream);
            downloadFile.FileContentStream.Position = 0;
            return(downloadFile);
        }
コード例 #8
0
        public async Task DownloadFile(string path, string filename, string sasUri, bool append = false, CancellationToken token = default(CancellationToken))
        {
            DownloadFileModel model = new DownloadFileModel(path, filename, sasUri, append);

            byte[]         message  = GetMessage(model);
            MethodRequest  request  = new MethodRequest("downloadFile", message);
            MethodResponse response = await client.InvokeMethodAsync(deviceId, moduleId, request);

            if (response.Status != 200)
            {
                Console.WriteLine("DirectMethods Client DownloadFile2 failed");
            }
        }
コード例 #9
0
        private async Task <MethodResponse> DownloadFileHandler(MethodRequest request, object context)
        {
            int response = 200;

            try
            {
                string            jsonString = request.DataAsJson;
                DownloadFileModel model      = JsonConvert.DeserializeObject <DownloadFileModel>(jsonString);
                if (!model.Cancel)
                {
                    string key = FixPath(model.BlobPath) + model.BlobFilename;

                    if (downloadTokenSources.ContainsKey(key))
                    {
                        downloadTokenSources.Remove(key);
                    }

                    CancellationTokenSource cts = new CancellationTokenSource();
                    downloadTokenSources.Add(key, cts);

                    if (string.IsNullOrEmpty(model.SasUri))
                    {
                        //await remote.DownloadFile(model.Path, model.Filename, model.BlobPath, model.BlobFilename, model.Append);
                        InternalDownloadFile(model.Path, model.Filename, model.BlobPath, model.BlobFilename, model.Append, cts.Token);
                    }
                    else
                    {
                        InternalDownloadFile(model.Path, model.Filename, model.SasUri, model.Append, cts.Token);
                        //await remote.DownloadFile(model.Path, model.Filename, model.SasUri, model.Append, cts.Token);
                    }
                }
                else
                {
                    string key = FixPath(model.BlobPath) + model.BlobFilename;
                    if (downloadTokenSources.ContainsKey(key))
                    {
                        CancellationTokenSource cts = downloadTokenSources[key];
                        cts.Cancel();
                    }
                    downloadTokenSources.Remove(key);
                }
            }
            catch (Exception ex)
            {
                response = 500;
                Console.WriteLine("ERROR: DirectMethods-DownloadFileHandler '{0}'", ex.Message);
            }


            return(new MethodResponse(response));
        }
コード例 #10
0
        public DownloadFileModel RetrieveUploadErrorsFile(string blobAddress)
        {
            var memoryStream = new MemoryStream();
            var container    = BlobClient.CreateContainer(ServiceFileContainerName);

            container.DownloadToStream(blobAddress, memoryStream);
            var downloadFile = new DownloadFileModel
            {
                FileName          = blobAddress,
                FileContentStream = memoryStream
            };

            downloadFile.FileContentStream.Position = 0;
            return(downloadFile);
        }
コード例 #11
0
        public IActionResult DownloadFile([FromBody] DownloadFileModel model)
        {
            try
            {
                var file = _taskInteractor.GetTaskDetails(model.TaskId);

                if (file == null)
                {
                    return(null);
                }

                if (file.Documents.Count() == 0)
                {
                    return(null);
                }

                var    fileDetails = file.Documents.Where(x => x.Id == model.ItemId).FirstOrDefault();
                string filepath    = Path.Combine(_settings.DocumentsPath, fileDetails.Task.ProjectId.ToString(), fileDetails.FileName);

                if (!System.IO.File.Exists(filepath))
                {
                    throw new ArgumentException("Invalid file name or file does not exist!");
                }

                byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
                var    fs        = new FileStream(filepath, FileMode.Open);
                var    ms        = new MemoryStream();
                ms.CopyTo(fs);


                var    ext         = Path.GetExtension(filepath).ToLowerInvariant();
                string contentType = _fileManager.GetContentType()[ext];

                Response.ContentType = contentType;
                Response.Headers.Add("Content-Disposition", "attachment; filename=" + fileDetails.FileName);

                //return File(memory, contentType);
                //return File(fileBytes, "application/force-download", fileDetails.FileName);
                return(PhysicalFile(filepath, "application/force-download", fileDetails.FileName));
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
コード例 #12
0
        public IActionResult DownloadData([FromBody] DownloadFileModel downloadFile)
        {
            var asset = _libraryDataService.GetAsset(downloadFile.Id);

            if (asset == null)
            {
                return(NotFound());
            }

            byte[] fileData = _dataFileService.TryGetFile(asset, downloadFile.Type);

            if (fileData == null)
            {
                return(NotFound());
            }

            var fileName = Regex.Replace(asset.Title, @"[^a-zA-z0-9]+", String.Empty) + "." + downloadFile.Type;

            return(File(fileData, System.Net.Mime.MediaTypeNames.Application.Octet, fileName));
        }
コード例 #13
0
        public HttpResponseMessage GetFile([FromBody] DownloadFileModel model)
        {
            string filePath           = _fileService.GetFilePathById(model.id);
            string downloadedFileName = Path.GetFileName(filePath);

            //converting Pdf file into bytes array
            var dataBytes = System.IO.File.ReadAllBytes(filePath);
            //adding bytes to memory stream
            var dataStream     = new MemoryStream(dataBytes);
            var bufferedStream = new BufferedStream(dataStream);

            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);

            httpResponseMessage.Content = new StreamContent(dataStream);
            httpResponseMessage.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            httpResponseMessage.Content.Headers.ContentDisposition.FileName = downloadedFileName;
            httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

            return(httpResponseMessage);
        }
コード例 #14
0
        public HttpResponseMessage DownloadData([FromBody] DownloadFileModel Dfile)
        {
            var asset = assets.GetById(Dfile.Id);

            if (asset == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            FileDataBase fileData = new FileDataHandler();

            byte[] downFile = fileData.TryGetFile(asset, Dfile.Type);

            if (downFile == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var filename = Regex.Replace(asset.Title, @"[^a-zA-z0-9]+", String.Empty) + "." + Dfile.Type;

            return(GetFile(downFile, filename));
        }
コード例 #15
0
        public async Task Insert(DownloadFileModel file)
        {
            string sql = "INSERT INTO `downloadfiles` (DownloadId, Filename) VALUES (@DownloadId, @Filename)";

            await _sqlDataAccess.SaveData(sql, file);
        }
コード例 #16
0
 public async Task Post(DownloadFileModel file, byte[] contents)
 {
     string uri = $"https://{HostUri}/upload/{file.DownloadId}/{file.Filename}";
     await _httpDataAccess.Post(uri, Convert.ToBase64String(contents));
 }
コード例 #17
0
        public async Task <DownloadFileModel> FetchMediaFile(string mediaId)
        {
            DownloadFileModel result = null;

            var url = _addressConfig.DownloadFileUrl;

            _client.QueryString.Add("media_id", mediaId);
            //var result= _client.Get(url);
            _client.Headers[System.Net.HttpRequestHeader.ContentType] = "";
            var data = await _client.DownloadDataTaskAsync(url);

            int testHeaderMaxLength = 100;
            var testHeaderBuffer    = new byte[(data.Length < testHeaderMaxLength ? data.Length : testHeaderMaxLength)];

            Array.Copy(data, 0, testHeaderBuffer, 0, testHeaderBuffer.Length);
            Encoding encoder       = Encoding.UTF8;
            String   testHeaderStr = encoder.GetString(testHeaderBuffer);

            if (testHeaderStr.StartsWith("--"))
            {//正常返回数据时,第一行数据为分界线,而分界线必然以"--"开始.
                var    tempArr            = testHeaderStr.Split(new String[] { Environment.NewLine }, StringSplitOptions.None);
                string boundary           = tempArr[0] + Environment.NewLine;
                int    boundaryByteLength = encoder.GetBytes(boundary).Length;
                byte[] destData           = new byte[data.Length - boundaryByteLength];
                Array.Copy(data, boundaryByteLength, destData, 0, destData.Length);
                result = new DownloadFileModel();

                result.Data = destData;

                const string Content_Length = "Content-Length";
                if (_client.ResponseHeaders == null || (!_client.ResponseHeaders.AllKeys.Contains(Content_Length)))
                {
                    result.FileLength = -1;
                }

                var lengthStr = _client.ResponseHeaders[Content_Length];
                int length    = 0;
                if (int.TryParse(lengthStr, out length))
                {
                    result.FileLength = length;
                }
                else
                {
                    result.FileLength = 0;
                }

                const string Content_Type = "Content-Type";
                if (_client.ResponseHeaders == null || (!_client.ResponseHeaders.AllKeys.Contains(Content_Type)))
                {
                    result.FileType = "unknown";
                }
                else
                {
                    result.FileType = _client.ResponseHeaders[Content_Type];
                }
            }
            else
            {
                string resultJson = encoder.GetString(data);
            }
            return(result);
        }
コード例 #18
0
        public async Task DeleteByFile(DownloadFileModel file)
        {
            string sql = "DELETE FROM `downloadfiles` WHERE `DownloadId` = @DownloadId AND `Filename` = @Filename";

            await _sqlDataAccess.SaveData(sql, file);
        }