关于文件的上传。

asp.net里的代码:
        <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
            
<input type="file" runat="server" id="UploadImage" name="UploadImage">
            
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
            
<asp:Label id="lblMsg" runat="server" ForeColor="Red"></asp:Label>
        
</form>
button的事件如下:
        private void Button1_Click(object sender, System.EventArgs e)
        
{
            
string all_filename,this_filename,ext_filename,new_filename;
            
            
if(UploadImage.PostedFile.ContentLength==0)
            
{
                
this.lblMsg.Text="该文件不存在。";
            }

            
else
            
{
                all_filename
=UploadImage.PostedFile.FileName;
                
string[] a=all_filename.Split("\\".ToCharArray());
                this_filename
=a[a.Length-1].ToString();
                ext_filename
=this_filename.Remove(0,this_filename.LastIndexOf("."));
                new_filename
=System.Guid.NewGuid()+ext_filename;

                UploadImage.PostedFile.SaveAs(Server.MapPath(
"/sourcefile"+ @"\c1\" + new_filename);
                
            }

        }


以上是对单个文件的上传的方法,如果要同时实现多文件的上传。代码如下:
这是asp.net页面里的代码,注意新添加的file可以不需要id和name的
        <form id="Form1" method="post" encType="multipart/form-data" runat="server">
            
<P><input id="UploadImage" type="file" name="UploadImage" runat="server"><br>
                
<input type="file" runat="server"><br>
                
<input type="file" runat="server"></P>
            
<P>&nbsp;
                
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
                
<asp:Label id="lblMsg" runat="server" ForeColor="Red"></asp:Label></P>
        
</form>

c#代码部分
        {
            
for(int i=0;i<Request.Files.Count;i++)
            
{
                System.Web.HttpPostedFile myfile
=Request.Files[i];

                
string all_filename,this_filename,ext_filename,new_filename;
            
                
if(myfile.ContentLength!=0)
                
{
                    all_filename
=myfile.FileName;
                    
string[] a=all_filename.Split("\\".ToCharArray());
                    this_filename
=a[a.Length-1].ToString();
                    ext_filename
=this_filename.Remove(0,this_filename.LastIndexOf("."));
                    new_filename
=System.Guid.NewGuid()+ext_filename;

                    myfile.SaveAs(Server.MapPath(
"/sourcefile"+ @"\c1\" + new_filename);
                }

            }


        }
原文地址:https://www.cnblogs.com/songafeng/p/168801.html