C# MVC controller 上传附件及下载附件(笔记)

描述:Microsoft.AspNetCore.Http.IFormFileCollection 实现附件快速上传功能代码。

上传附件代码

        [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类定义

    public class upLoadFile
    {
        public string mingcheng { get; set; }
        public Microsoft.AspNetCore.Http.IFormFileCollection files { get; set; }
        public string miaoshu { get; set; }
    }

附件下载代码:

      [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;
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值