zoukankan      html  css  js  c++  java
  • 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");   
            }

  • 相关阅读:
    iOS真机调试 for Xcode 5
    iOS/iphone开发如何为苹果开发者帐号APPID续费
    unity3d中布娃娃系统
    U3D实现与iOS交互
    两种方法连接MySql数据库
    Unity3D Gamecenter 得分上传失败的处理
    Unity3.5 GameCenter基础教程(转载)
    判断数字正则表达式
    (转)SQL server 2005查询数据库表的数量和表的数据量
    C#操作PowerDesigner代码
  • 原文地址:https://www.cnblogs.com/delusion/p/13361503.html
Copyright © 2011-2022 走看看