.net core下对于附件上传下载的实现示例

本篇主要介绍下文件的上传与下载。分享给大家,具体如下:

文件上传下载也是系统中常用的功能,不啰嗦,直接上代码看下具体的实现。

文件上传

.net core通过 IFormFile 接收文件对象,再通过流的方式保存至指定的地方。

[HttpPost("upload")] //[DisableRequestSizeLimit] //禁用http限制大小 [RequestSizeLimit(100*1024*1024)] //限制http大小 public async Task<IActionResult> Post(List<IFormFile> files) { try { if (files == null || !files.Any()) return AssertNotFound(new ResponseFileResult { Result = false, Code = ResponseCode.InvalidParameters, ErrorMessage = "附件不能为空" }); 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 }); } }

其中http会默认限制一定的上传文件大小,可通过 [DisableRequestSizeLimit] 禁用http限制大小,也可通过 [RequestSizeLimit(1024)] 来指定限制http上传的大小。

文件下载

相对于上传,下载就比较简单了,找到指定的文件,转换成流,通过.net core自带的 File 方法返回流文件,完成文件下载:

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

总结

文件的上传下载的基本操作简单介绍了下,大家可以尝试下。以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdspwz.html