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;
        }
相关推荐
小小代码团2 小时前
2026 Office Online Server (全网最新/最详细/含问题修复) 终极部署教程
windows·microsoft·c#
Li.CQ2 小时前
SQL学习笔记(二)
笔记·sql·学习
自不量力的A同学3 小时前
OpenNJet v3.3.1.3
笔记
lzhdim3 小时前
C#开发者必知的100个黑科技(前50)!从主构造函数到源生成器全面掌握
开发语言·科技·c#
charlie1145141914 小时前
如何快速在 VS2026 上使用 C++ 模块 — 完整上手指南
开发语言·c++·笔记·学习·现代c++
yong99904 小时前
基于C#与三菱FX5U PLC实现以太网通信
网络·c#·php
可信计算5 小时前
【算法随想】一种基于“视觉表征图”拓扑变化的NLP序列预测新范式
人工智能·笔记·python·算法·自然语言处理
CreasyChan5 小时前
C#特性(Attributes)详解
开发语言·c#
历程里程碑5 小时前
C++ 9 stack_queue:数据结构的核心奥秘
java·开发语言·数据结构·c++·windows·笔记·算法
CreasyChan6 小时前
C# 委托/事件/UnityEvent 详解
开发语言·c#