我之前有一个FileUpload控件可以在数据库中单独上传每个文件。但现在我希望能够批量上传。
我的要求是csv文件包含文件名和文件路径,我需要使用FileUpload上传csv并最终运行读取csv的代码并将每个文件插入表ApplicantAttachment。 ApplicantAttachment具有列fileName(NVARCHAR),FilePath(NVARCHAR),附件(VARBINARY)。在这个附件列中,我需要保存csv中提到的文件的二进制格式。 我的CSV看起来像这样 FileName FilePath dl-54a.pdf c:\ users \ abc \ desktop \ dl-54a.pdf xyz.doc c:\ users \ abc \ desktop \ xyz.doc
我希望我能做到这样的事情。但我知道我们将文件名等文件放到Fileupload对象上。任何的意见都将会有帮助。
<asp:FileUpload ID="csvFile" runat="server" Width="400" /></td>
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="btnUpload_Click" /></td>
protected void btnUpload_Click(object sender, EventArgs e)
{
if (csvFile.HasFile)
{
List<string[]> filesToUpload = parseCSV(csvFile.PostedFile.FileName);
SaveFiles(filesToUpload);
}
}
public List<string[]> parseCSV(string path)
{
List<string[]> parsedData = new List<string[]>();
try
{
using (StreamReader readFile = new StreamReader(path))
{
string line;
string[] row;
while ((line = readFile.ReadLine()) != null)
{
if (!readFile.ReadLine().Contains("ApplicantId"))
{
row = line.Split(',');
parsedData.Add(row);
}
}
}
}
catch (Exception e)
{
;
}
return parsedData;
}
private void SaveFiles(List<string[]> files)
{
foreach (string[] attachment in files)
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
FileUpload fu = new FileUpload();
fu.FileName = attachment[1].ToString();
if (fu.HasFile)
{
ApplicantAttachment aa1 = new ApplicantAttachment();
aa1.Filename = attachment[0].ToString();
aa1.FileType = fu.PostedFile.ContentType;
aa1.Attachment = fu.FileBytes;
db.ApplicantAttachments.InsertOnSubmit(aa1);
db.SubmitChanges();
}
}
}
}
答案 0 :(得分:0)
这是有效的。无法使用FileUpload。
private void SaveFiles(List<string[]> files)
{
foreach (string[] attachment in files)
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
string path = attachment[1].ToString();
byte[] fileBytes = File.ReadAllBytes(path);
ApplicantAttachment aa1 = new ApplicantAttachment();
aa1.Filename = attachment[0].ToString();
aa1.FileType = MIMEType.GetType(attachment[1].ToString());
aa1.Attachment = fileBytes;
db.ApplicantAttachments.InsertOnSubmit(aa1);
db.SubmitChanges();
}
}
}