C# Web如何实现文件上传的示例详解

1 第一种上传方式,基本通用于 net所有的框架[HttpPost][Route( "Common uploadFile1 ")]public string upl

1.第一种上传方式,基本通用于.net所有的框架

        [HttpPost]
        [Route("Common/uploadFile1")]
        public string uploads()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象
            HttpFileCollectionBase files = request.Files;
            string fileSuffix = Path.GetExtension(files[0].FileName).ToLower();
            string fileId = Guid.NewGuid().ToString();
            string dateKey = DateTime.Now.ToString("yyyyMMdd");
            string savaPath, uri;     
            uri = @"/fileData/rest/" + dateKey + @"/";
            savaPath = request.MapPath(uri);
            if (!Directory.Exists(savaPath))
            {
                Directory.CreateDirectory(savaPath);
            }
            try
            {
                files[0].SaveAs(savaPath + fileId + fileSuffix);
                return uri + fileId + fileSuffix;
            }catch (Exception ex){
                return ex.Message;
            }
        }

2.WebAPI可以用这个来,但是在低一点的版本没有IFormFile 这个对象

        /// <summary>
        /// 通用文件上传接口
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Common/uploadFile2")]
        public  async Task<Axios<string>>  upload(IFormFile file)
        {
            string fileSuffix = Path.GetExtension(file.FileName).ToLower();
            string fileId = Guid.NewGuid().ToString();
            string dateKey = DateTime.Now.ToString("yyyyMMdd");
            string savaPath,uri;
            uri = @"/fileData/rest/"  + dateKey  + @"/";
            savaPath =  Path.Combine(Directory.GetCurrentDirectory(), uri);
            if (!Directory.Exists(savaPath)){Directory.CreateDirectory(savaPath);}
            //创建特定名称的文件流
            await using var stream = new FileStream(savaPath + fileId + fileSuffix, FileMode.Create);
            try
            {
                //上传文件
                await file.CopyToAsync(stream);
                stream.Flush();
                return Axios<string>.ok(uri + fileId + fileSuffix);
            } catch (Exception ex)  {
                //上传异常处理 
                return Axios<string>.fail(ex.Message);
            }

3.上传方式,可以用于.netCore MVC方式的文件上传

        [HttpPost]
        public JsonResult uploadX(HttpPostedFileBase file)
        {
            String suffix = file.FileName.Substring(file.FileName.LastIndexOf(".", StringComparison.Ordinal));
            string fileName = Guid.NewGuid().ToString().Replace("-", "") + suffix;
            string uri = string.Format("{0}/{1}/{2}/", "fileData", "rest", DateTime.Now.Year+""+DateTime.Now.Month +""+ DateTime.Now.Day);
            string filePath = Server.MapPath(string.Format("~/{0}",uri));
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            file.SaveAs(Path.Combine(filePath, fileName));
            return Json(uri + fileName);
        }

注:以上就是三种文件上传的方式,可以采用第一种方式,兼容性好

到此这篇关于C# Web实现文件上传的示例详解的文章就介绍到这了,更多相关C#文件上传内容请搜索好代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好代码网!

标签: C 文件 上传