ASP.NET 上传文件的两种方法

前言

  在做项目的过程需要做上传的功能,所以小编写个博客园来记录一下,方便以后查看,写得不好请勿喷

  本章节讲的是文件的上传,有些前端上传的时候传递的数据是不一样的,在这里讲两种形式上传的方式:

  1.通过文件流方式上传文件

  2.通过二进制流方式上传文件

一、文件流方式

     private const string _exts = ".doc,.docx";
     /// <summary>
        /// 上传.doc,.docx,.pdf 通过文件流上传
        /// </summary>
        /// <returns></returns>
        //[AdminAccountValidate]
        [Route("Upload"),HttpPost]
        public ResponseModel<UploadResponseModel> Upload()
        {
            var response = new ResponseModel<UploadResponseModel>();
            HttpFileCollection files = HttpContext.Current.Request.Files;
            if (files.Count > 0)
            {
                var fileExt = Path.GetExtension(files[0].FileName);

                if (!_exts.Contains(fileExt))
                {
                    response.Fail(AllMsg.UnsupportFileType);
                    return response;
                }

                if (files[0].ContentLength > AllConfig.CommonStaticConfigInfo.MaxFileSize * 1024)
                {
                    response.Fails(AllMsg.MaxFile);
                    return response;
                }

                string saveTempPath = AllConfig.CommonStaticConfigInfo.ContractTemplateUrl;
                string path = "UploadFiles/ContractTemplate/" + fileExt + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                string fileName = Guid.NewGuid().ToString().ToLower() + fileExt;
                string morePath = saveTempPath + path;
                if (!Directory.Exists(morePath))
                {
                    Directory.CreateDirectory(morePath);
                }
                files[0].SaveAs(saveTempPath + path + fileName);

                response.PostContent = new UploadResponseModel()
                {
                    Address = path + fileName,
                    FileName = files[0].FileName,
                    FileType = fileExt
                };
            }
            return response;
        }

二、二进制流方式

     /// <summary>
        /// 上传.doc,.docx,.pdf 通过二进制流上传
        /// </summary>
        /// <returns></returns>
        //[AdminAccountValidate]
        [Route("Upload"),HttpPost]
        public async Task<ResponseModel<UploadResponseModel>> Upload()
        {
            
            ResponseModel<UploadResponseModel> response = new ResponseModel<UploadResponseModel>();
            var request = HttpContext.Current.Request;
            string strFileName = request["FileName"];
            var bytes = request.BinaryRead(request.TotalBytes);
            if (bytes.Length > 0)
            {
                //前两个字节代表文件类型,这里以 JPG 类型为例
                var bs = bytes[0].ToString() + bytes[1].ToString();
                var fileExt = "";
                if (bs.Equals("208207"))
                {
                    fileExt = ".doc";
                }
                else
                {
                    response.Fail(AllMsg.UnsupportFileType);
                    return response;

                }
                string saveTempPath = AllConfig.CommonStaticConfigInfo.ContractTemplateUrl;
                string path = "UploadFiles/ContractTemplate/" + fileExt + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                string fileName = Guid.NewGuid().ToString().ToLower() + fileExt;
                string morePath = saveTempPath + path;
                if (!Directory.Exists(morePath))
                {
                    Directory.CreateDirectory(morePath);
                }
                await Task.Run(() =>
                {
                    using (FileStream fs = new FileStream(saveTempPath + path + fileName, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                    }
                });
                response.PostContent = new UploadResponseModel()
                {
                    Address = path + fileName,
                    FileName = strFileName,
                    FileType = fileExt
                };

            }
            return response;
        }

这篇文章只做为一个备忘录嘻嘻....

posted @ 2020-01-15 17:14  糯米雪梨  阅读(451)  评论(0编辑  收藏  举报