.net core中对于附件上传下载的示例分析
这篇文章主要介绍.net core中对于附件上传下载的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
本篇主要介绍下文件的上传与下载。分享给大家,具体如下:
文件上传下载也是系统中常用的功能,不啰嗦,直接上代码看下具体的实现。
文件上传
.net core通过 IFormFile 接收文件对象,再通过流的方式保存至指定的地方。
[HttpPost("upload")]//[DisableRequestSizeLimit]//禁用http限制大小[RequestSizeLimit(100*1024*1024)]//限制http大小publicasyncTask<IActionResult>Post(List<IFormFile>files){try{if(files==null||!files.Any())returnAssertNotFound(newResponseFileResult{Result=false,Code=ResponseCode.InvalidParameters,ErrorMessage="附件不能为空"});stringfilePath=Path.Combine(Directory.GetCurrentDirectory(),BASEFILE,$@"Template");if(!Directory.Exists(filePath))Directory.CreateDirectory(filePath);varresult=newResponseFileResult();varfileList=newList<FileResultModel>();foreach(varfileinfiles){varfileModel=newFileResultModel();varfileName=ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');varnewName=Guid.NewGuid().ToString()+Path.GetExtension(fileName);varfilefullPath=Path.Combine(filePath,$@"{newName}");using(FileStreamfs=newFileStream(filefullPath,FileMode.Create))//System.IO.File.Create(filefullPath){file.CopyTo(fs);fs.Flush();}fileList.Add(newFileResultModel{Name=fileName,Size=file.Length,Url=$@"/file/download?fileName={newName}"});}result.FileResultList=fileList;returnAssertNotFound(result);}catch(Exceptionex){returnAssertNotFound(newResponseFileResult{Result=false,Code=ResponseCode.UnknownException,ErrorMessage=ex.Message});}}
其中http会默认限制一定的上传文件大小,可通过 [DisableRequestSizeLimit] 禁用http限制大小,也可通过 [RequestSizeLimit(1024)] 来指定限制http上传的大小。
文件下载
相对于上传,下载就比较简单了,找到指定的文件,转换成流,通过.net core自带的 File 方法返回流文件,完成文件下载:
[HttpGet("download")]publicasyncTask<IActionResult>Get(stringfileName){try{varaddrUrl=Path.Combine(Directory.GetCurrentDirectory(),BASEFILE,$@"{fileName}");FileStreamfs=newFileStream(addrUrl,FileMode.Open);returnFile(fs,"application/vnd.android.package-archive",fileName);}catch(Exceptionex){returnNotFound();}}
以上是“.net core中对于附件上传下载的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。