zoukankan      html  css  js  c++  java
  • ASP.Net中上传文件的几种方法

    转自:https://www.cnblogs.com/gxwang/p/4883902.html

    在做Web项目时,上传文件是经常会碰到的需求。ASP.Net的WebForm开发模式中,封装了FileUpload控件,可以方便的进行文件上传操作。但有时,你可能不希望使用ASP.Net中的服务器控件,仅仅使用Input标签来实现文件上传。当然也是可以的。下面总结在项目中使用过的上传文件的方式。

    一、使用Asp.Net中的FileUpload服务器端控件实现上传

    使用asp.net中的服务器端控件FileUpload上传文件非常方便。FileUpload对上传操作进行了封装,你只需要调用SaveAs方法即可完成上传。下面是简单的上传代码。

        <p>服务器端控件上传</p>
        <asp:FileUpload ID="MyFileUpload" runat="server" /> 
            <asp:Button ID="FileUploadButton" runat="server" Text="上传" 
                onclick="FileUploadButton_Click" />
    复制代码
     1    protected void FileUploadButton_Click(object sender, EventArgs e)
     2         {
     3             if (MyFileUpload.HasFile)
     4             {
     5                 string filePath = Server.MapPath("~/UploadFiles/");
     6                 string fileName = MyFileUpload.PostedFile.FileName;
     7                 MyFileUpload.SaveAs(filePath + fileName);
     8                 Response.Write("<p >上传成功!</p>");
     9             }
    10             else
    11             {
    12                 Response.Write("<p >请选择要上传的文件!</p>");
    13             }
    14         }
    复制代码

    当然,在实际项目中就不能这么简单的保存文件了。你至少得增加一些文件类型的判断,防止用户上传一些能够威胁到系统安全的文件。你可以采用客户端JS验证的方式,也能够在.cs的服务器端代码中验证。

    在asp.Net WebForm开发框架下,我们也可以利用Html的Input标签来上传文件。这时候需要注意的一点,这个type为file的Input标签需要加上runat="server"属性,否则在后台Request.Files获取不到上传的文件。

      <p>使用Html的Input标签上传</p>
        <input type="file" name="MyFileUploadInput" runat="server" /><asp:Button 
                ID="InputFileUploadButton" runat="server" Text="上传" 
                onclick="InputFileUploadButton_Click" />
    复制代码
     1         protected void InputFileUploadButton_Click(object sender, EventArgs e)
     2         {
     3             HttpFileCollection files = Request.Files;
     4             string filePath = Server.MapPath("~/UploadFiles/");
     5             if (files.Count != 0)
     6             {
     7                 string fileName = files[0].FileName;
     8                 files[0].SaveAs(Path.Combine(filePath, fileName));
     9                 Response.Write("<p>上传成功</p>");
    10             }
    11             else
    12             {
    13                 Response.Write("<p>未获取到Files:"+ files.Count.ToString()+"</p>");
    14             }
    15         }
    复制代码

    以这种方式进行上传的时候,好处就是可以方便的用JS生成多个Input标签来上传多个文件。且此时需要注意的是,Input标签必须要有name属性。在后台,只需要循环调用SaveAs()方法即可。

    接下来的两种上传方式(二和三)都会用到Ajax异步提交数据,后台使用一个.ashx文件进行处理。两种方式共用一个文件,ajax传入的url参数中加一个method来区分哪种方式传过来的。后台代码如下:

    复制代码
     1    public void ProcessRequest(HttpContext context)
     2         {
     3             string method = context.Request.QueryString["method"].ToString();
     4             switch (method)
     5             {
     6                 case "ajaxFileUpload":
     7                     ajaxFileUpload(context);
     8                     break;
     9                 case "formDataUpload":
    10                     formDataUpload(context);
    11                     break;
    12                 default:
    13                     break;
    14             }
    15         }
    16 
    17         private static void formDataUpload(HttpContext context)
    18         {
    19             HttpFileCollection files = context.Request.Files;
    20 
    21             string msg = string.Empty;
    22             string error = string.Empty;
    23             if (files.Count > 0)
    24             {
    25                 files[0].SaveAs(ConfigurationManager.AppSettings["FilePath"].ToString() + System.IO.Path.GetFileName(files[0].FileName));
    26                 msg = " 成功! 文件大小为:" + files[0].ContentLength;
    27                 string res = "{ error:'" + error + "', msg:'" + msg + "'}";
    28                 context.Response.Write(res);
    29                 context.Response.End();
    30             }
    31         }
    32 
    33         private static void ajaxFileUpload(HttpContext context)
    34         {
    35             HttpFileCollection files = context.Request.Files;
    36 
    37             string msg = string.Empty;
    38             string error = string.Empty;
    39             if (files.Count > 0)
    40             {
    41                 files[0].SaveAs(ConfigurationManager.AppSettings["FilePath"].ToString() + System.IO.Path.GetFileName(files[0].FileName));
    42                 msg = " 成功! 文件大小为:" + files[0].ContentLength;
    43                 string res = "{ error:'" + error + "', msg:'" + msg + "'}";
    44                 context.Response.Write(res);
    45                 context.Response.End();
    46             }
    47         }
    复制代码

    二、使用Html中的Input标签加FormData对象实现

    使用这种方式上传附件,对浏览器有些要求。FormData属于Html5中新增的特性,IE浏览器只有在10以上才支持。所以,个中利弊自己权衡,但用起来觉得方便。下面直接上代码:

    复制代码
     1   function formDataUpload() {
     2             var fileupload = document.getElementById('fileToUpload').files;
     3             var formdata = new FormData();
     4             formdata.append('files', fileupload[0]);
     5             var xmlHttp = new XMLHttpRequest();
     6             xmlHttp.open("post", 'Handlers/FileUpload.ashx?method=formDataUpload');
     7             xmlHttp.onreadystatechange = function () {
     8                 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
     9                     alert('上传成功');
    10                 }
    11             }
    12             xmlHttp.send(formdata);
    13         }
    复制代码

    三、使用Jquery中的ajaxfileupload.js插件实现上传

    使用此方法,需要引用jquery.js和ajaxfileupload.js两个文件。还需要注意的部分是两个文件的版本匹配问题,可能在使用过程中会出现些异常。此时发挥搜索引擎的作用,总能找到你需要的解决方案。

    JavaScript代码如下:

    复制代码
     1     function ajaxFileUpLoad() {
     2         $.ajaxFileUpload(
     3             {
     4                 url: 'Handlers/FileUpload.ashx?method=ajaxFileUpload',
     5                 secureuri: false,
     6                 fileElementId: 'fileToUpload',
     7                 dataType: 'json',
     8                 success: function (data, status) {
     9                     $('#img1').attr("src", data.imgurl);
    10                     if (typeof (data.error) != 'undefined') {
    11                         if (data.error != '') {
    12                             alert(data.error);
    13                         } else {
    14                             alert(data.msg);
    15                         }
    16                     }
    17                 },
    18                 error: function (data, status, e) {
    19                     alert(e);
    20                 }
    21             }
    22         )
    23         return false;
    24     }
    复制代码

    Html页面上的代码如下:

    复制代码
     1 <html xmlns="http://www.w3.org/1999/xhtml">
     2 <head>
     3 <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
     4 <script type="text/javascript" src="Scripts/ajaxfileupload.js"></script>
     5 <script type="text/javascript">
     6     $(function () {
     7         $("#ajaxfileuploadButton").click(function () {
     8             ajaxFileUpLoad();
     9         })
    10 
    11         $("#formdataButton").click(function () {
    12             formDataUpload();
    13         })
    14     });
    15 
    16 </script>
    17     <title></title>
    18     <script type="text/javascript">
    19      
    20     </script>
    21 </head>
    22 <body>
    23 <input type="file" id="fileToUpload" name="fileToUpload" />
    24 <input type="button" id="ajaxfileuploadButton" value="ajaxfileupload插件上传" />
    25 <input type="button" id="formdataButton" value="FormData方式上传" />
    26 </body>
    27 </html>
    复制代码

    总结

    以上总结了几种上传文件的方式,也简单的说明了一些使用中需要注意的问题。当然,可能遇到的问题还不止这些,如果在开发过程中还遇到了其他稀奇古怪的问题,可自行搜索相关问题。每一次针对遇到的问题的解决,都是对这方面的知识一次更深入的理解。在不断解决问题中慢慢进步。

  • 相关阅读:
    【LeetCode】048. Rotate Image
    【LeetCode】036. Valid Sudoku
    【LeetCode】060. Permutation Sequence
    【LeetCode】001. Two Sum
    【LeetCode】128. Longest Consecutive Sequence
    【LeetCode】081. Search in Rotated Sorted Array II
    【LeetCode】033. Search in Rotated Sorted Array
    顺时针打印矩阵
    矩形覆盖
    二维数组中的查找
  • 原文地址:https://www.cnblogs.com/zhangwei99com/p/8717281.html
Copyright © 2011-2022 走看看