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;
        }
相关推荐
兴趣使然_1 小时前
【笔记】使用 html 创建网址快捷方式
笔记·html·js
aramae2 小时前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
fen_fen3 小时前
学习笔记(32):matplotlib绘制简单图表-数据分布图
笔记·学习·matplotlib
水果里面有苹果6 小时前
20-C#构造函数--虚方法
java·前端·c#
饕餮争锋7 小时前
设计模式笔记_创建型_建造者模式
笔记·设计模式·建造者模式
萝卜青今天也要开心7 小时前
2025年上半年软件设计师考后分享
笔记·学习
吃货界的硬件攻城狮7 小时前
【STM32 学习笔记】SPI通信协议
笔记·stm32·学习
蓝染yy8 小时前
Apache
笔记
lxiaoj1119 小时前
Python文件操作笔记
笔记·python