asp.net文件上传

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 ekin7913046 的 blog

public void uploadfile(object sender , eventargs e)
  {
   //检查上传文件不为空
   if(myfile.postedfile!=null)
   {    
    string nam = myfile.postedfile.filename ;
    //取得文件名(抱括路径)里最后一个"."的索引
    int i= nam.lastindexof(".");
    //取得文件扩展名
    string newext =nam.substring(i);
    //这里我自动根据日期和文件大小不同为文件命名,确保文件名不重复
    datetime now = datetime.now;
    string newname=now.dayofyear.tostring()+myfile.postedfile.contentlength.tostring();

    //保存文件到你所要的目录,这里是iis根目录下的uploadfiles目录
    //注意: 我这里用server.mappath()取当前文件的绝对目录.在asp.net里"\"必须用"\\"代替
    myfile.postedfile.saveas(server.mappath(".\\uploadfiles\\"+newname+newext));
    
    //得到这个文件的相关属性:文件名,文件类型,文件大小
    fname.text=myfile.postedfile.filename;
    fenc.text=myfile.postedfile.contenttype ;
    fsize.text=myfile.postedfile.contentlength.tostring();
    image1.imageurl = "http://localhost/web/news/uploadfiles/"+newname+newext;
   }
  }

html页面代码

<%@ page language="c#" codebehind="webform2.aspx.cs" autoeventwireup="false" inherits="web.news.webform2" %>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
 <head>
  <title>webform2</title>
  <meta content="microsoft visual studio .net 7.1" name="generator">
  <meta content="c#" name="code_language">
  <meta content="javascript" name="vs_defaultclientscript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetschema">
  <script language="c#" runat="server">
 //this method is called when the "upload" button id pressed

  </script>
 </head>
 <body ms_positioning="gridlayout">
  <form id="form1" method="post" runat="server">
   <input id="myfile" style="z-index: 101; left: 408px; position: absolute; top: 224px" type="file"
    name="myfile" runat="server">
   <asp:button id="button1" style="z-index: 102; left: 496px; position: absolute; top: 304px" onclick="uploadfile"
    runat="server" text="上传"></asp:button>
   <table cellspacing="2" border="1">
    <tr>
     <td><b>文件资料</b></td>
     <td>&nbsp;</td>
    </tr>
    <tr>
     <td>文件名 :</td>
     <td><asp:label id="fname" runat="server" text=""></asp:label></td>
    </tr>
    <tr>
     <td>文件类型 :</td>
     <td><asp:label id="fenc" runat="server"></asp:label></td>
    </tr>
    <tr>
     <td>文件大小 :(in bytes)</td>
     <td><asp:label id="fsize" runat="server" /></td>
    </tr>
   </table>
   <asp:image id="image1" style="z-index: 103; left: 112px; position: absolute; top: 160px" runat="server"
    width="200px" height="224px"></asp:image>
  </form>
 </body>
</html>

本文关键:asp.net文件上传
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top