• Web文件上传


          从客户端上传文件到服务器端,

          一般来讲,做应用系统, 总是会遇到从客户端通过Web页面上传文件到服务器端的需求.

    这种需求一般都会想做批量上传.

          但是HTML中的input上传, 一个input控件只能选择一个文件, 同时上传多文件, 如果做到简单易用就需要花点时间了.

          网上基本的做法都是google的那种上载文件的 模式, 就是先一个一个选择, 然后批量上传, 这种模式虽然不是非常方便, 但是也还好使.

    demo代码就不用自己写了, 上网上荡了一个, 希望原创作者不要见怪.


    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo._Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <script language="JavaScript">
    function addFile()
    {
     var str = '<INPUT type="file" size="50" NAME="File">'
     document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
    }
    </script>
    <html xmlns="
    http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server" enctype="multipart/form-data">
               <input type="button" value="增加(Add)" onclick="addFile()">

      <input onclick="this.form.reset()" type="button" value="重置(ReSet)">
              <asp:Button Runat="server" Text="上传" ID="Upload" OnClick="Upload_Click1" ></asp:Button>
        <div id="MyFile">
             <input type="file" name="File" />
        </div>
        </form>
    </body>
    </html>

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    namespace Demo
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
            }
            protected void Upload_Click1(object sender, EventArgs e)
            {

                HttpFileCollection _files = System.Web.HttpContext.Current.Request.Files;

                for (int i = 0; i < _files.Count; i++)
                {
                    _files[i].SaveAs(Server.MapPath("~/Files/" + _files[i].FileName));
                }
            }
        }
    }

     这段代码中尤其需要注意 enctype="multipart/form-data",这在上传文件的时候尤其需要注意, W3C对这个的解释如下:

    enctype = content-type [CI]

    This attribute specifies the content type used to submit the form to the server (when the value of method is "post"). The default value for this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" should be used in combination with the INPUT element,type="file".  

  • 相关阅读:
    Java B/S开发模式漫谈 (转)
    struts 使用多个配置文件 strutsconfig.xml
    java 验证邮箱格式正确性、验证字符串是否为数字
    Java获取各种常用时间方法
    创建HttpServlet的基本步骤
    struts1.x 配置文件之——web.xml详解
    最常用的JAVA包
    字符串转换为日期时间格式
    struts1.x 配置文件详解
    看看别人的博客,经验总结,很宝贵
  • 原文地址:https://www.cnblogs.com/dunnice/p/1402087.html
Copyright © 2020-2023  润新知