The implementation of upload and download of attachment under. net core

In last article Some operation and use of Excel under. net core This paper mainly introduces the operation of excel under. net core. This paper mainly introduces the upload and download of the file.

File upload and download is also a common function in the system, not verbose, 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 through stream.

[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 });
    }
}

The http will limit the size of the uploaded file by default. You can disable the http limit by [DisableRequestSizeLimit], or you can specify the limit by [RequestSizeLimit(1024)].

File download

Compared with upload, download is simpler. Find the specified File, convert it to stream, return the stream File through the File method of. net core, and 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();
    }
}

summary

The basic operation of file upload and download is introduced briefly. You can try it.

Tags: ASP.NET Excel Android

Posted on Sun, 15 Dec 2019 11:39:08 -0500 by Fastback_68