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;
        }
相关推荐
XGeFei4 小时前
【AI应用/Agent智能体搭建平台2】Dify——自部署
人工智能·笔记·学习
祈禾4 小时前
Redis三大缓存问题与分布式锁
运维·数据库·redis·笔记·分布式·缓存
rockey6277 小时前
基于AScript的Lua脚本语言发布啦
c#·.net·lua·script·动态脚本
IT古董7 小时前
【MES学习笔记系列】MES 厂商与产品对比
笔记·学习
wangyue_msn_868 小时前
Agent知识学习笔记——03 RAG
笔记·学习·ai编程
嘶哈哈哈8 小时前
# 异构十电机机架数学建模:从单电机力矩到受约束控制分配
笔记
呱呱巨基8 小时前
Linux 查找命令
linux·笔记·学习·查找命令
zhangrelay9 小时前
ROS 2 Lyrical 第4章 URDF机器人建模与Gazebo Garden仿真
linux·笔记·学习·ubuntu·机器人·ros2
疯狂打码的少年10 小时前
【数据结构】串的模式匹配:KMP算法(重点)
数据结构·笔记·算法
一米阳光866110 小时前
软考(中级)软件设计师核心笔记(8)数据结构——线性结构、数组、矩阵
数据结构·笔记·职场发展·软考·软件设计师·中级职称