我有一个包含现有行和附件ID的SQL数据库。我有一个需要插入此数据库的数千个PDF文件的文件夹。应根据文件名/列将文件插入每一行。例。一个名为123.pdf的文件应插入ID为123的行中。我使用Ajax文件上载工具创建了一个Asp.net Web表单应用程序。如果我使用真实的目录,它工作正常。如何使用临时目录执行此操作?
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string filePath = e.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
string tempPath = System.IO.Path.GetTempFileName();
AjaxFileUpload1.SaveAs(tempPath);
using (FileStream fs = File.OpenRead(tempPath))
{
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//How do I create a temp directory of the files in the AjaxFileUploader?
var dir = new DirectoryInfo(CreateTempDirectoryHere);
FileInfo[] pdfFiles = dir.GetFiles();
foreach (FileInfo pdfFile in pdfFiles)
{
var attachmentID = Path.GetFileNameWithoutExtension(pdfFile.ToString());
string constr = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("dbo.spUploadContentBulk", con);
cmd.Parameters.AddWithValue("@AttachmentID", attachmentID);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "@FileName",
Value = filename
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "@FileContent",
Value = bytes
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "@FileType",
Value = contenttype
});
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
File.Delete(tempPath);
}
}
catch (Exception ex)
{
txtError.Text = ex.ToString();
}
}
我的意思是更像这样的东西(甚至不使用临时文件夹):
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string filename = e.FileName;
var bytes = e.GetContents();
var attachmentID = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
string constr = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("dbo.spUploadContentBulk", con);
cmd.Parameters.AddWithValue("@AttachmentID", attachmentID);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "@FileName",
Value = filename
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "@FileContent",
Value = bytes
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "@FileType",
Value = contenttype
});
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
catch (Exception ex)
{
txtError.Text = ex.ToString();
}
}