找不到要上传的文件

时间:2013-12-27 16:51:28

标签: c# asp.net

我正在尝试通过服务器中的以下代码将excel文件上传到sql数据库

我可以在服务器中打开excel文件,但我无法通过asp页面将此文件上传到sql。它显示即使我通过文件浏览器控件选择文件也找不到文件。我浏览时屏幕上显示文件名。但是当我点击上传按钮时,找不到它。请帮帮我

我的C#代码就是这个

   protected void btnUpload_Click(object sender, EventArgs e)
    {
       if (fileuploadExcel.HasFile)
        {
           SqlConnection conn1 = new SqlConnection(str);
        //file upload path


        string path = fileuploadExcel.PostedFile.FileName;


        //Create connection string to Excel work book
        string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
        //Create Connection to Excel work book
        OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
        //Create OleDbCommand to fetch data from Excel
        OleDbCommand cmd = new OleDbCommand("Select [Date],[PName],[SQE Reived],[SQE processed] from [Sheet1$]", excelConnection);
        excelConnection.Open();
        OleDbDataReader dReader;
        dReader = cmd.ExecuteReader();
        SqlBulkCopy sqlBulk = new SqlBulkCopy(conn1);
        //Give your Destination table name
        conn1.Open();
        sqlBulk.DestinationTableName = "SQE";
        sqlBulk.WriteToServer(dReader);
        excelConnection.Close();
    }
}

我的asp页面macrkup

<table>
 <tr>
 <td>
 <asp:Button ID="Button1" Text="Upload Productivity data in to iConnect"     runat="server" CssClass="style88"  
                     Font-Bold="False" Height="36px" Width="750px" Font-        Names="Calibri" ForeColor="White" Font-Size ="large"   Border-radius="0px 0px 0px 0px"
                                       ></asp:Button>

   </td>
      </tr>
     <tr>
      <td>
      <a href="SQEprTemplate.xlsx">Download Template for upload</a>

    <br />
     <br />

 </td>

 <tr>
 <td>
  <asp:Panel ID="Panel1" runat="server">
         <asp:FileUpload ID="fileuploadExcel" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" 
           onclick="btnUpload_Click" />
        <br/>

     </asp:Panel>


 </td>

 </tr>



 </tr>
 </table>

2 个答案:

答案 0 :(得分:0)

我非常肯定path已经包含了驱动器号,但是您将D:\\附加到下一行的开头。

... Source=D:\\" + path ...

尝试删除D:\\

答案 1 :(得分:0)

fileuploadExcel.PostedFile.FileName客户端计算机上的名称,完整路径 该文件在服务器计算机中不存在,您需要在尝试使用它之前保存它

string serverFolder = Server.MapPath("APP_DATA");
string serverFile = Path.Combine(serverFolder, Path.GetFileName(fileuploadExcel.PostedFile.FileName));
fileuploadExcel.PostedFile.SaveAs(serverFile);
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" + 
                               @"Data Source=" + serverFile + 
                               @";Extended Properties=Excel 12.0;Persist Security Info=False";