12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using Bowin.Common.Utility;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Configuration;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- using System.Threading.Tasks;
- namespace Bowin.Common.Files
- {
- public static class FileHelper
- {
- private static FileSettings Settings { get; set; }
- static FileHelper()
- {
- var configuration = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json")
- .Build();
- Settings = configuration.GetSection("FileSettings").Get<FileSettings>();
- }
- public async static Task<string> Upload(IFormFile formFile)
- {
- string directory = Settings.FilePath + "/" + DateTime.Now.ToString("yyyyMM");
- string filePath = directory + "/" + Guid.NewGuid() + Path.GetExtension(formFile.FileName);
- if (!Directory.Exists(HttpHelper.MapPath(directory)))
- {
- Directory.CreateDirectory(HttpHelper.MapPath(directory));
- }
- using (var stream = System.IO.File.Create(HttpHelper.MapPath(filePath)))
- {
- await formFile.CopyToAsync(stream);
- }
- return filePath;
- }
- public static FileStream GetFileStream(string filePath)
- {
- var stream = System.IO.File.OpenRead(HttpHelper.MapPath(filePath));
- return stream;
- }
- public static MemoryStream GetMemoryStream(string filePath, bool isDelete)
- {
- string physicalPath = HttpHelper.MapPath(filePath);
- var fileStream = System.IO.File.Open(physicalPath, System.IO.FileMode.Open);
- var data = new byte[fileStream.Length];
- fileStream.Read(data);
- fileStream.Close();
- var memoryStream = new MemoryStream(data);
- if (isDelete)
- {
- System.IO.File.Delete(physicalPath);
- }
- return memoryStream;
- }
- }
- public class FileSettings
- {
- public string FilePath { get; set; }
- }
- }
|