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;
        }
相关推荐
Panda__Panda2 小时前
docker项目打包演示项目(数字排序服务)
运维·javascript·python·docker·容器·c#
weixin_456904272 小时前
基于.NET Framework 4.0的串口通信
开发语言·c#·.net
Tiger_shl3 小时前
C# 预处理指令 (# 指令) 详解
开发语言·c#
sali-tec4 小时前
C# 基于halcon的视觉工作流-章45-网格面划痕
开发语言·算法·计算机视觉·c#
sealaugh325 小时前
AI(学习笔记第十二课) 使用langsmith的agents
人工智能·笔记·学习
QZ_orz_freedom5 小时前
学习笔记--事务管理
笔记·学习
程序员大雄学编程5 小时前
「机器学习笔记14」集成学习全面解析:从Bagging到Boosting的Python实战指南
笔记·机器学习·集成学习
im_AMBER6 小时前
Web 开发 30
前端·笔记·后端·学习·web
试试勇气6 小时前
Linux学习笔记(八)--环境变量与进程地址空间
linux·笔记·学习
蒙奇D索大6 小时前
【数据结构】考研数据结构核心考点:平衡二叉树(AVL树)详解——平衡因子与4大旋转操作入门指南
数据结构·笔记·学习·考研·改行学it