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

2025-05-29 0 37

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

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

文件上传

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45
[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 方法返回流文件,完成文件下载

?

1

2

3

4

5

6

7

8

9

10

11

12

13

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

}

}

总结

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

原文链接:https://www.jianshu.com/p/99af019284ab

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 .net core下对于附件上传下载的实现示例 https://www.kuaiidc.com/98081.html

相关文章

发表评论
暂无评论