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);
                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();
            }
        }

 

转载于:https://www.cnblogs.com/zhangxiaoshuai/p/11208525.html

你可能感兴趣的:(Net Core 文件的上传下载)