示例#1
0
        public static async Task CreateZipFileFromDirectoryAsync(string sourcePath, string destionationFile)
        {
            if (!System.IO.Directory.Exists(sourcePath))
            {
                throw new System.IO.DirectoryNotFoundException(sourcePath);
            }

            Queue <string> folderQueue = new Queue <string>();

            folderQueue.Enqueue(sourcePath);

            using (System.IO.FileStream fs = new System.IO.FileStream(destionationFile, System.IO.FileMode.Create))
                using (System.IO.Compression.ZipArchive zipArchive = new System.IO.Compression.ZipArchive(fs, System.IO.Compression.ZipArchiveMode.Create, false))
                {
                    while (folderQueue.Count != 0)
                    {
                        System.IO.DirectoryInfo folderInfo = new System.IO.DirectoryInfo(folderQueue.Dequeue());

                        foreach (var subDir in folderInfo.EnumerateDirectories("*.*", System.IO.SearchOption.TopDirectoryOnly))
                        {
                            folderQueue.Enqueue(subDir.FullName);
                        }

                        foreach (var file in folderInfo.GetFiles("*.*", System.IO.SearchOption.TopDirectoryOnly))
                        {
                            string entryPath = System.IO.Path.GetRelativePath(sourcePath, file.FullName);
                            var    e         = zipArchive.CreateEntry(entryPath);

                            using (var entry = e.Open())
                                using (System.IO.FileStream fi = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open))
                                    await fi.CopyToAsync(entry);
                        }
                    }
                }
        }
示例#2
0
        static async Task CollectFilesAsync(IEnumerable <string> paths, List <string> comicFiles, List <ImageReference> images)
        {
            foreach (var path in paths)
            {
                try
                {
                    if (System.IO.Directory.Exists(path))
                    {
                        await CollectFilesAsync(System.IO.Directory.EnumerateFileSystemEntries(path), comicFiles, images).ConfigureAwait(false);

                        continue;
                    }
                    if (!System.IO.File.Exists(path))
                    {
                        continue;
                    }
                    if (FileHeader.Load(path) != null)
                    {
                        comicFiles.Add(path);
                        continue;
                    }
                    if (!imageExtensions.Any(ex => string.Equals(System.IO.Path.GetExtension(path), "." + ex, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                            await fs.CopyToAsync(ms).ConfigureAwait(false);
                        images.Add(new ImageReference(ms.ToArray()));
                    }
                }
                catch (UnauthorizedAccessException) { }
            }
        }
示例#3
0
        internal static async Task CopyFileAsyncInternal(string sourceFilePath, string destinationFilePath, CancellationToken cancellationToken, int bufferSize)
        {
            var fileOptions = System.IO.FileOptions.Asynchronous | System.IO.FileOptions.SequentialScan;

            using (var sourceStream = new System.IO.FileStream(sourceFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, bufferSize, fileOptions))
                using (var destinationStream = new System.IO.FileStream(destinationFilePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.None, bufferSize, fileOptions)) {
                    await sourceStream.CopyToAsync(destinationStream, bufferSize, cancellationToken);
                }
        }
        private async Task <bool> UploadArquivoAlternativo(IFormFile arquivo, string imgPrefixo)
        {
            if (arquivo == null || arquivo.Length <= 0)
            {
                NotificarErro("Forneça uma Imagem para o produto!");
                return(false);
            }

            var filePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot/imagens", imgPrefixo + arquivo.FileName);

            if (System.IO.File.Exists(filePath))
            {
                NotificarErro("Já existe um arquivo com este nome!");
                return(false);
            }

            using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
            {
                await stream.CopyToAsync(stream);
            }

            return(true);
        }
示例#5
0
        public async Task <IActionResult> Download([FromQuery] int Id)
        {
            var result = await FileRepository.GetFile(Id);

            if (result != null)
            {
                string path     = HostingEnvironment.ContentRootPath;
                string fileName = System.IO.Path.GetFileName(result.Url);
                string fullPath = System.IO.Path.Combine(path, @"Upload", fileName);

                var memory = new System.IO.MemoryStream();
                using (var stream = new System.IO.FileStream(fullPath, System.IO.FileMode.Open))
                {
                    await stream.CopyToAsync(memory);
                }
                memory.Position = 0;

                return(File(memory, result.ContentType, result.Url));
            }
            else
            {
                return(null);
            }
        }
示例#6
0
 public override Task CopyToAsync(System.IO.Stream destination, int bufferSize, CancellationToken cancellationToken)
 {
     return(InternalFileStream.CopyToAsync(destination, bufferSize));
 }
        public async Task <IActionResult> DownloadMeasureTemplate(Guid metricID, string format)
        {
            var metric = await _db.Metrics.Where(m => m.ID == metricID).Select(m => new { m.Title, ResultsType = m.ResultsType.Value }).FirstOrDefaultAsync();

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

            if (string.Equals("json", format, StringComparison.OrdinalIgnoreCase))
            {
                var measure = new Models.MeasureSubmissionViewModel {
                    MetricID    = metricID,
                    ResultsType = metric.ResultsType,
                    Measures    = new HashSet <Models.MeasurementSubmissionViewModel> {
                        new Models.MeasurementSubmissionViewModel {
                            Definition = string.Empty, RawValue = string.Empty, Measure = 0, Total = 0
                        }
                    }
                };

                var serializerSettings = new Newtonsoft.Json.JsonSerializerSettings {
                    Formatting = Formatting.Indented, DateFormatString = "'yyyy-MM-dd'"
                };
                var result = new FileContentResult(System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(measure, serializerSettings)), Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"))
                {
                    FileDownloadName = CleanFilename("MeasureSubmission_" + metric.Title) + ".json"
                };

                return(result);
            }
            else if (string.Equals("xlsx", format, StringComparison.OrdinalIgnoreCase))
            {
                using (var scope = _serviceProvider.CreateScope())
                {
                    var hostingEnvironment = scope.ServiceProvider.GetService <IWebHostEnvironment>();

                    System.IO.MemoryStream ms = new System.IO.MemoryStream();

                    using (var fs = new System.IO.FileStream(System.IO.Path.Combine(hostingEnvironment.WebRootPath, "assets", "MeasureSubmission_template.xlsx"), System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        await fs.CopyToAsync(ms);

                        await fs.FlushAsync();
                    }

                    ms.Position = 0;

                    using (var document = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(ms, true))
                    {
                        var helper = new Utils.MeasuresExcelReader(document);
                        helper.UpdateMetricInformation(metricID, metric.ResultsType);
                        helper.Document.Save();
                        document.Close();
                    }

                    ms.Position = 0;

                    var result = new FileStreamResult(ms, Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    {
                        FileDownloadName = CleanFilename("MeasureSubmission_" + metric.Title + ".xlsx")
                    };

                    return(result);
                }
            }

            return(BadRequest("Invalid document format, must be either 'json' or 'xlsx'."));
        }
示例#8
0
        public async Task <IActionResult> Upload([FromForm] IFormFile uploadFile)
        {
            var nowStamp = DateTime.Now;
            var rootPath = _env.ContentRootPath;

            if (uploadFile == null)
            {
                return(NoContent());
            }

            // 根据现有信息创建文件实体
            var file = new File {
                FileName = uploadFile.FileName, Type = uploadFile.ContentType, UploadDate = nowStamp
            };

            if (uploadFile.Length > 0)
            {
                using (var stream = new System.IO.MemoryStream())
                {
                    // 读取上传文件计算 MD5
                    await uploadFile.CopyToAsync(stream);

                    stream.Position = 0;
                    var md5Arr = MD5.Create().ComputeHash(stream);

                    StringBuilder sBuilder = new StringBuilder();

                    for (int i = 0; i < md5Arr.Length; i++)
                    {
                        // x2 代表转为 16 进制长度为 2 的 string
                        sBuilder.Append(md5Arr[i].ToString("x2"));
                    }

                    file.MD5 = sBuilder.ToString();

                    // 将文件内容转为字节数组并写入实体
                    file.FileContent = stream.ToArray();

                    var extension = "";

                    // 处理特定的文档预览
                    switch (file.Type)
                    {
                    case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                        extension = ".docx";
                        break;

                    case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                        extension = ".xlsx";
                        break;

                    case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                        extension = ".pptx";
                        break;

                    case "application/msword":
                        extension = ".doc";
                        break;

                    case "application/vnd.ms-excel":
                        extension = ".xls";
                        break;

                    case "application/vnd.ms-powerpoint":
                        extension = ".ppt";
                        break;

                    case "application/pdf":
                        extension = ".pdf";
                        break;
                    }

                    if (extension != "")
                    {
                        // 进行预览图片的生成并写入到实体中
                        var resultImage = CovertFile.Covert(rootPath, file.MD5, extension, stream);

                        if (System.IO.File.Exists(resultImage))
                        {
                            using (var previewStream = new System.IO.FileStream(resultImage, System.IO.FileMode.Open))
                            {
                                await stream.FlushAsync();

                                stream.Position = 0;
                                await previewStream.CopyToAsync(stream);

                                file.PreviewImage = stream.ToArray();
                            }

                            // 删除临时生成的图片
                            System.IO.File.Delete(resultImage);
                        }
                    }
                }

                // 将生成的实体添加到 Model 中并与数据库同步
                await _context.File.AddAsync(file);

                _context.SaveChanges();

                return(Ok(new FileReturnInfo(file)));
            }
            else
            {
                return(NoContent());
            }
        }