2

我正在使用我发现的帖子中的一个示例。这似乎很适合我正在做的事情。这是保存文件的代码:

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase excelFile)
{
   //Save the uploaded file to the disc.
   string savedFileName = "~/App_Data/uploads/";// +excelFile.FileName;
   string filePath = Path.Combine(savedFileName, excelFile.FileName); 
   excelFile.SaveAs(Server.MapPath(filePath));

   return View();
}

以下是将数据放入数据库表的代码:

private void SaveFileToDatabase(string savedFileName)
{
    String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='catalog=QQAEntities'Integrated Security=SSPI;User Instance=True";
    String connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", Server.MapPath(savedFileName));
    {
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
       using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [dbo_ts_quality_audit_tbl$]", connection))
       {
          connection.Open();

          using (OleDbDataReader dReader = cmd.ExecuteReader())
          {
             using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
             {
                 //Give your Destination table name 
                 sqlBulk.DestinationTableName = "AuditSchedules";
                 sqlBulk.WriteToServer(dReader);
             }
          }
       }
       }
   }
}

private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
   //System.Web.UI.WebControls.WebControl
   string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);

   fileUploadControl.SaveAs(filePath);

   return filePath;
}

这是 FileUpload 的视图:

<h2>FileUpload</h2>

@using (Html.BeginForm("FileUpload", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="excelFile" name="excelFile" />
<input type="submit" value="Upload" />
}

上传工作。我的问题是;如何SaveFileToDatabase在视图中调用数据传输 ()?这一切都将在管理部分完成。

此外,我已经在配置中连接到数据库 - 我该如何清理它?

谢谢

4

1 回答 1

1

视图应该获取文件信息,然后将所有执行传递给控制器​​。在控制器内部,您应该调用 SaveFileToDatabase 函数并将您保存的临时文件传递给它,如下所示:

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase excelFile)
{
    //Save the uploaded file to the disc.
    string savedFileName = "~/App_Data/uploads/";// +excelFile.FileName;
    string filePath = Path.Combine(savedFileName, excelFile.FileName); 
    excelFile.SaveAs(Server.MapPath(filePath));

    // Call function to place temporary file into database
    SaveFileToDatabase(filePath);

    // Optional: Delete temporary Excel file from server

    return View();
}

(不要忘记考虑是否要在服务器上保留临时 Excel 文件。如果没有,一旦知道处理已完成,您需要注意删除文件)

于 2012-06-29T19:50:01.840 回答