.net实现文件上传到服务器

RT,把excel文件上传到服务器上去,然后打开服务器上的路径进行读取excel的内容。该如何实现。望高人指点,在线等。。写谢谢了。

1、前端界面十分简单,只是放一个file类型的和一个按钮,并且为这个按钮添加点击事件(btnUpLoad_Click),如下图:

<input id="UpLoad" runat="server" type="file">
</asp:button>

2、后台编写上传按钮点击事件UpLoad_Click里的代码,先大体说一下思路:

    根据file类型的控件获得将要上传文件在本机的物理路径;

    在这个物理路径中用截取字符串的方法获得文件名(第一步中取得的路径为本机的绝对路径,在服务器上是无效的,所以这里只需要获取文件名);

    利用file类型的控件属性PostedFile的SaveAs()方法将相应文件存储到服务器中指定的文件夹中。

3、后台核心代码:

protected void btnUpLoad_Click(object sender, EventArgs e)
    {
        //取出所选文件的本地路径
        string fullFileName = this.UpLoad.PostedFile.FileName;
        //从路径中截取出文件名
        string fileName = fullFileName.Substring(fullFileName.LastIndexOf(\) + 1);
        //限定上传文件的格式
        string type = fullFileName.Substring(fullFileName.LastIndexOf(.) + 1);
        if (type == doc || type == docx || type == xls || type == xlsx || type == ppt || type == pptx || type == pdf || type == jpg || type == bmp || type == gif || type == png || type == txt || type == zip || type == rar)
        {
            //将文件保存在服务器中根目录下的files文件夹中
            string saveFileName = Server.MapPath(/files) + \ + fileName;
            UpLoad.PostedFile.SaveAs(saveFileName);
            Page.ClientScript.RegisterStartupScript(Page.GetType(), message, <script language='javascript' defer>alert('文件上传成功!');</script>);
 
            //向数据库中存储相应通知的附件的目录
            BLL.news.InsertAnnexBLL insertAnnex = new BLL.news.InsertAnnexBLL();
            AnnexEntity annex=new AnnexEntity();     //创建附件的实体
            annex.AnnexName=fileName;               //附件名
            annex.AnnexContent=saveFileName;        //附件的存储路径
            annex.NoticeId = noticeId;              //附件所属“通知”的ID在这里为已知
            insertAnnex.InsertAnnex(annex);         //将实体存入数据库(其实就是讲实体的这些属性insert到数据库中的过程,具体BLL层和DAL层的代码这里不再多说)
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(Page.GetType(), message, <script language='javascript' defer>alert('请选择正确的格式');</script>);
        }
    }
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-11-14
if (FilePath.HasFile == false)
{
ShowJS("没有文件");
return;
}
DataTable dt_excel = GetTableType();
string filepath = string.Empty;
filepath = FilePath.PostedFile.FileName;
string filename = FilePath.FileName;
string savepath = Server.MapPath(Request.ApplicationPath + "\\ExcelFiles\\");
string dir = Path.GetDirectoryName(savepath);
if (Directory.Exists(dir) == true)
{
Directory.CreateDirectory(dir);
}
string[] arr = Directory.GetFiles(dir, filename);
string fname = filename.Substring(0, filename.LastIndexOf('.'));
int m = 0;
while (arr.Length > 0)
{
m++;
filename = fname + m + Path.GetExtension(filename);
arr = Directory.GetFiles(dir, filename);
}
filepath = savepath + filename;
FilePath.PostedFile.SaveAs(filepath);
dt_excel = PublicWay.ReadExcel(filepath, dt_excel);//读取Excel到DataTable中
File.Delete(filepath);

PublicWay是一个自己写的方法,你可以加我,我传给你,或者用邮箱也可以追问

邮箱:[email protected]

本回答被网友采纳