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

  • 相关阅读:
    服务器安全之修改3389远程桌面端口小工具(包源码)
    CYQ.Data.ProjectTool 项目配置工具发布(包源码)
    爱奇艺视频广告拦截失败,发文共商大计
    开发者基础知识游戏,共10关,欢迎挑战
    秋天新作品:秋式广告杀手,每年帮大伙多活78天!
    MySql Blob图片类型存储Bug解决:索引超出了数组界限错误
    爱奇艺视频广告拦截失败,发文共商大计
    简说宽带商的弹窗广告进化及网站应对之策(DNS劫持进化论)
    秋式广告杀手技术分享:网络请求基础知识
    通用社区登陆组件技术分享(开源)中篇:OAuth 登陆组件流程及组件集成方法
  • 原文地址:https://www.cnblogs.com/delusion/p/13361503.html
Copyright © 2011-2022 走看看