Implementation example of uploading and downloading attachments under. net core

  • 2021-10-25 06:19:15
  • OfStack

This article mainly introduces the uploading and downloading of the following files. Share it with you as follows:

File uploading and downloading is also a common function in the system, not wordy, directly on the code to see the specific implementation.

File upload

. net core receives the file object through IFormFile, and then saves it to the specified place by streaming.


[HttpPost("upload")]
//[DisableRequestSizeLimit] // Disable http Limit size 
[RequestSizeLimit(100*1024*1024)] // Limit http Size 
public async Task<IActionResult> Post(List<IFormFile> files)
{
  try
  {
    if (files == null || !files.Any())
      return AssertNotFound(new ResponseFileResult { Result = false, Code = ResponseCode.InvalidParameters, ErrorMessage = " Attachment cannot be empty " });


    string filePath = Path.Combine(Directory.GetCurrentDirectory(), BASEFILE, $@"Template");
    if (!Directory.Exists(filePath))
      Directory.CreateDirectory(filePath);

    var result = new ResponseFileResult();
    var fileList = new List<FileResultModel>();

    foreach (var file in files)
    {
      var fileModel = new FileResultModel();
      var fileName = ContentDispositionHeaderValue
              .Parse(file.ContentDisposition)
              .FileName
              .Trim('"');
      var newName = Guid.NewGuid().ToString() + Path.GetExtension(fileName);
      var filefullPath = Path.Combine(filePath, $@"{newName}");

      using (FileStream fs = new FileStream(filefullPath, FileMode.Create))//System.IO.File.Create(filefullPath)
      {
        file.CopyTo(fs);
        fs.Flush();
      }


      fileList.Add(new FileResultModel { Name = fileName, Size = file.Length, Url = $@"/file/download?fileName={newName}" });
    }
    result.FileResultList = fileList;
    return AssertNotFound(result);
  }
  catch(Exception ex)
  {
    return AssertNotFound(new ResponseFileResult { Result = false, Code = ResponseCode.UnknownException, ErrorMessage = ex.Message });
  }
}

Among them, http will limit the upload file size by default, and http can be disabled by [DisableRequestSizeLimit], or RequestSizeLimit (1024) can be specified to limit the upload size of http.

File download

Compared with uploading, downloading is relatively simple. Find the specified file, convert it into a stream, and return the stream file through the File method provided by. net core to complete the file download:


[HttpGet("download")]
public async Task<IActionResult> Get(string fileName)
{
  try
  {
    var addrUrl = Path.Combine(Directory.GetCurrentDirectory(), BASEFILE, $@"{fileName}");
    FileStream fs = new FileStream(addrUrl, FileMode.Open);
    return File(fs, "application/vnd.android.package-archive", fileName);
  }
  catch(Exception ex)
  {
    return NotFound();
  }
}

Summarize


Related articles: