C# MVC controller 上传附件及下载附件(笔记)

描述:Microsoft.AspNetCore.Http.IFormFileCollection 实现附件快速上传功能代码。

上传附件代码

csharp 复制代码
        [Route("myUploadFile")]
        [HttpPost]
        public ActionResult MyUploadFile([FromForm] upLoadFile rfile)
        {
            string newFileName = Guid.NewGuid().ToString("N") + rfile.mingcheng;
            string dirPath = Path.Combine(new string[] { Environment.CurrentDirectory, "wwwroot", "File", "FileUpload", newFileName });
            if (System.IO.Directory.Exists(dirPath))
            {
                System.IO.Directory.CreateDirectory(dirPath);
                System.Threading.Thread.Sleep(0);
            }
            string filePath = Path.Combine(new string[] { dirPath, newFileName });
            var t = Request.Form.Files[0];
            using (FileStream fs = System.IO.File.Open(filePath, FileMode.OpenOrCreate))
            {
                string fileName = rfile.files[0].FileName;
                byte[] bs = new byte[rfile.files[0].Length];
                GetPicThumbnail(rfile.files[0].OpenReadStream()).Read(bs, 0, bs.Length);
                fs.Write(bs, 0, bs.Length);
                fs.Close();
            }
            return new ObjectResult(new { code = "1", msg = "文件上传成功" });
        }

upLoadFile Model类定义

csharp 复制代码
    public class upLoadFile
    {
        public string mingcheng { get; set; }
        public Microsoft.AspNetCore.Http.IFormFileCollection files { get; set; }
        public string miaoshu { get; set; }
    }

附件下载代码:

csharp 复制代码
      [Route("myGetFile")]
        [HttpGet]
        public ActionResult MyGetFile(string id)
        {
                PhysicalFileResult f = new PhysicalFileResult(@"E:\work\codes\技术积累\临时\weixinshare\weixinshare\weixinshare\wwwroot\File\weixinimg\2edf0b9324cb44edaa7d73ea46ab0b15.jpg"
                   , "application/file");
                f.FileDownloadName = "ddd.jpg";
                f.EnableRangeProcessing = true;
                f.LastModified = DateTimeOffset.Now;
                return f;
        }
相关推荐
csdn_aspnet3 小时前
如何用 C# 和 Gemma 3 在本地构建一个真正能完成工作的 AI 代理的
人工智能·ai·c#·gemma
我是唐青枫4 小时前
C#.NET Span 深入解析:零拷贝内存切片与高性能实战
开发语言·c#·.net
左左右右左右摇晃5 小时前
HashMap 扩容机制
笔记
2301_781143566 小时前
C语言学习笔记
笔记·学习
蒸蒸yyyyzwd7 小时前
高并发40问学习笔记
笔记·学习
咕白m6259 小时前
C# 高效复制 Word 文档内容
后端·c#
Amazing_Cacao10 小时前
褪去故事滤镜:重建精品可可的“结构语言”
笔记·学习
日更嵌入式的打工仔11 小时前
二值信号量 vs 互斥量
笔记
Rolay11 小时前
打印功能开发历程,解决百分之九十九的打印需求
c#·打印机·c#打印优化
Try,多训练11 小时前
论文排版之添加图片、表格、公式的题注
经验分享·笔记