在VS2008中,使用<asp:UploadFile控件
前台页面
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="WebApplication1.FileUpload" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>无标题</title>
- <script type="text/javascript">
- function checkType() {
- //得到上传文件的值
- var fileName = document.getElementById('FileUpLoad1').value;
- //返回String对象中字符串最后出现的位置。
- var seat = fileName.lastIndexOf(".");
- //返回位于String对象中指定位置的子字符串并转换为小写
- var extension = fileName.substring(seat).toLowerCase();
- var allowed = [".xls", ".xlsx"];
- for (var i = 0; i < allowed.length; i++) {
- if (!(allowed[i] != extension)) {
- return true;
- }
- }
- alert("不支持" + extension + "格式");
- return false;
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:FileUpload ID="FileUpLoad1" runat="server" />
- <br />
- <asp:Button ID="btnFileUpload" runat="server"
- Text="文件上传" OnClientClick="return checkType()"
- onclick="btnFileUpload_Click" />
- <asp:Label ID="lblMessage" runat="server"></asp:Label>
- </div>
- </form>
- </body>
- </html>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
namespace WebApplication1
{
public partial class FileUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnFileUpload_Click(object sender, EventArgs e)
{
if (FileUpLoad1.HasFile)
{
//判断文件是否小于4MB
if (FileUpLoad1.PostedFile.ContentLength < 4194304)
{
HttpPostedFile file = FileUpLoad1.PostedFile;
string str=file.FileName;
string filename2 = str.Substring(str.LastIndexOf(".")).ToString().Trim();
string filename1 = DateTime.Now.Ticks.ToString()+filename2;
file.SaveAs(Server.MapPath("./upload/"+filename1));//将用户上传的文件保存到服务器上.
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("./upload/"+filename1) + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection Oleconn = new OleDbConnection(strConn);
string strExcel = "";
OleDbDataAdapter excelCommand = null;
DataSet excel_ds = new DataSet();
strExcel = "select * from [sheet1$]";
try
{
Oleconn.Open();
excelCommand = new OleDbDataAdapter(strExcel, Oleconn);
excelCommand.Fill(excel_ds, "exdtSource");//得到dataset
lblMessage.Text = "上传成功!";
}
catch (Exception ex)
{
lblMessage.Text = "出现异常,无法上传!";
}
finally
{
Oleconn.Close();
Oleconn.Dispose();
}
}
else
{
lblMessage.Text = "上传文件不能大于10MB!";
}
}
else
{
lblMessage.Text = "尚未选择文件!";
}
}
}
}