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;
        }
相关推荐
影寂ldy1 小时前
C# 事件完整学习笔记(发布订阅 + 自定义事件 + 内置 EventHandler)
笔记·学习·c#
海绵宝宝的月光宝盒1 小时前
6-机械设计基础物理知识
经验分享·笔记·其他·职场和发展·课程设计·学习方法
闪闪发亮的小星星2 小时前
卫星通信、主要业务类型、组成
笔记
十月的皮皮2 小时前
C语言学习笔记20260612-菱形图案打印(两种写法)
c语言·笔记·学习
chase。2 小时前
【学习笔记】RIGVid:通过模仿生成视频实现机器人操作,无需物理演示
笔记·学习·音视频
kyle~2 小时前
DDS分布式实时系统---自省机制
开发语言·分布式·机器人·c#·接口·ros2
c7692 小时前
【文献笔记】Learn to Relax with LLMs: Solving COPs via Bidirectional Coevolution
论文阅读·人工智能·笔记·语言模型·论文笔记·提示工程
Java面试题总结3 小时前
MarkItDown 再次登顶GitHub榜
开发语言·c#·github
Bnews3 小时前
买家电一对一的定制服务推荐:2026年618期间的专业选择指南
经验分享·笔记
佛系豪豪吖3 小时前
AtomCode 部署流程与使用经验
笔记·chatgpt·github·ai编程·gitcode