.Net Core 文件的上传下载

这里是后台控制器中的代码

上传文件

        /// 
        /// 上传附件(单个附件)
        /// 
        /// 
        [HttpPost]
        public ActionResult UploadFile()
        {
            try
            {
                string Id = "";//记录返回的附件Id
                string filePath = "";//记录文件路径
                IFormFileCollection formFiles = Request.Form.Files;//获取上传的文件
                if (formFiles == null || formFiles.Count == 0)
                {
                    return Json(new { status = -1, message = "没有上传文件", filepath = "" });
                }
                IFormFile file = formFiles[0];
                string fileExtension = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);//获取文件名称后缀 
                //保存文件
                var stream=file.OpenReadStream();
                // 把 Stream 转换成 byte[] 
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始 
                stream.Seek(0, SeekOrigin.Begin);
                // 把 byte[] 写入文件 
                FileStream fs = new FileStream("D:\\"+file.FileName, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(bytes);
                bw.Close();
                fs.Close(); 
                return Json(new { success = true, status = 0, message = "上传成功",  filepath = "D:\\"+file.FileName, code = Id });        
            }

            catch (Exception ex)
            {
                return Json(new { success = false, status = -3, message = "上传失败", data = ex.Message, code = "" });
            }
        }

文件下载

        /// 
        /// 文件下载
        /// 
        /// 
        /// 
        [HttpGet]
        public IActionResult DownLoadFile(string url)
        {
            try
            {
                var stream = System.IO.File.OpenRead(url);
                //var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//推荐此方法
                string fileExt = Path.GetExtension(url);
                //获取文件的ContentType
                var provider = new FileExtensionContentTypeProvider();
                var memi = provider.Mappings[fileExt];
                return File(stream, memi, Path.GetFileName(url));
            }
            catch (Exception ex)
            {
                return NotFound();
            }
        }

如果是在实时动态生成文件,且需要删除生成的文件的情况下下载文件的话,建议使用FileContentResult实现,示例代码

        /// 
        /// 生成无pdf文件并下载
        /// 
        /// id
        /// 
        [HttpGet]
        public ActionResult CreateNoWaterPDF(string id)
        {
            try
            {
                string pdfPath = "";
                //生成pdf文件
                projectInfoApp.CreateNoWaterPDF(id, environment.ContentRootPath, out pdfPath);
                var stream = new FileStream(pdfPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                MemoryStream memoryStream = new MemoryStream();
                stream.CopyTo(memoryStream);
                stream.Close();
                memoryStream.Position = 0;
                //删除生成的pdf文件,减少冗余文件
                System.IO.File.Delete(pdfPath);               
                byte[] bt = memoryStream.ToArray();
                FileContentResult result = new FileContentResult(bt, "application/octet-stream");
                result.FileDownloadName = "申报书.pdf";
                return result;
            }
            catch (Exception e)
            {
                //return NoContent();
                return null;
            }
        }

 

你可能感兴趣的:(.Net,Core,C#)