松鼠的博客

导航

c# 文件上传与下载

文件上传:

  API 上传的方法:

   //上传的文件格式
        public string[] ExtentsfileName = new string[] { ".doc", ".xls", ".png", ".jpg" };
        //路径
        public string UrlPath = "/Upload/";
        /// <summary>
        ///响应对象 ,使用前先赋值
        /// </summary>
        public HttpResponse Response = HttpContext.Current.Response;
        public HttpRequest Request = HttpContext.Current.Request;
        //上传文件
        [HttpPost]
        public FileResult UpLoad()
        {
            if (Request.Files.Count > 0)
            {
                string FileUrlResult = "";
                foreach (string fn in Request.Files)
                {
                    var file = Request.Files[fn];
                    var extenfilename = Path.GetExtension(file.FileName);
                    //判断 路径是否存在
                    string path = HttpContext.Current.Server.MapPath(UrlPath);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    if (ExtentsfileName.Contains(extenfilename.ToLower()))
                    {
                        string urlfile = UrlPath + DateTime.Now.ToFileTime() + extenfilename;
                        string filepath = HttpContext.Current.Server.MapPath(urlfile);
                        file.SaveAs(filepath);

                    }
                    else
                    {
                        return new FileResult() { Code = -1, Msg = "只允许上传指定格式文件" + string.Join(",", ExtentsfileName), Url = "" };
                    }
                }
                return new FileResult() { Code = 0, Msg = "上传成功", Url = FileUrlResult };
            }
            else
            {
                return new FileResult() { Code = -1, Msg = "不能上传空文件", Url = "" };
            }
        }

  上传文件 客户端

 

使用 ajax 方法进行文件上传

 <input type="file" id="f1" />
<input type="button" value="文件上传" onclick="ff()" />
<script>
    //文件上传
    function ff() {
        var formData = new FormData();
        var file = document.getElementById("f1").files[0];
        formData.append("fileInfo", file);
        $.ajax({
            url: "http://localhost:62381/api/Default/UpLoad",
            type: "POST",
            data: formData,
            contentType: false,//必须false才会自动加上正确的Content-Type
            processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
            success: function (data) {
                if (data.Code < 0)
                    alert(data.Msg)
                else
                    alert(data.Url)
            },
            error: function (data) {
                alert("上传失败!");
            }
        });
    }
</script>

 

MVC 上传文件的方法:

   public ActionResult File(HttpPostedFileBase file)
   {    
         //using System.IO;
         //上传路径
         string path = Server.MapPath("~/kuk");
         string filename = Path.Combine(path, file.FileName);
         file.SaveAs(filename);
         //上传成功 返回 ok
         return Content("ok");
    }

视图:

 

 

 

文件下载:

API 下载方法:

   /// <summary>
        /// 下载文件 使用过DEMO
        /// using System.IO;

        [HttpGet]
        public void DownLoad(string Url)
        {
               string filePath = HttpContext.Current.Server.MapPath(Url);
               FileInfo fi = new FileInfo(filePath);
               DownLoad(fi.Name, fi.FullName);
        }
        /// <param name="downFileName">下载后保存名</param>
        /// <param name="sourceFileName">服务器端物理路径</param> public void DownLoad(string downFileName, string sourceFileName) { if (File.Exists(sourceFileName)) { Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", downFileName)); Response.Charset = "GB2312"; Response.ContentEncoding = Encoding.GetEncoding("GB2312"); Response.ContentType = MimeMapping.GetMimeMapping(downFileName); Response.WriteFile(sourceFileName); Response.Flush(); Response.Close(); } }

客户端显示:

 

MVC 下载方法:

 // 要引用 using System.IO;
        public ActionResult FileDownload()
        {
            string path = Server.MapPath("/kuk/");
            FileStream fs = new FileStream(path, FileMode.Open);
            return File(fs, "image/gif", "a.jpg");   
        }

 

 

参考文章:http://blog.ncmem.com/wordpress/2023/12/07/c-%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e4%b8%8e%e4%b8%8b%e8%bd%bd/

欢迎入群一起讨论

 

 

posted on 2023-12-07 14:02  Xproer-松鼠  阅读(63)  评论(0编辑  收藏  举报