![](/img/trans.png)
[英]Read Data from Notepad File and Store into a Table in SQL Server using ASP.NET MVC
[英]ASP.NET Store uploaded file sql server table
如何将ASP.net webform上载的文件存储到sql server 2005 varbinary(max)字段中?
这是我到目前为止:
protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
StoreFile(Request.Files[i]);
}
}
private void StoreFile(HttpPostedFile file)
{
// what do i do now?
}
一个普通的ado.net示例会很好。 一个linq to sql例子也是如此。
谢谢
有关如何将文件直接上传到4GuysFromRolla数据库的精彩教程
以下是我使用Linq To Sql的方法:
FilesDataContext db = new FilesDataContext();
protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
StoreFile(Request.Files[i]);
}
db.SubmitChanges();
}
private void StoreFile(HttpPostedFile file)
{
byte[] data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
File f = new File();
f.Data = data;
f.Filename = file.FileName;
db.Files.InsertOnSubmit(f);
}
这通常被认为是不好的形式。 它使您的数据库膨胀,并没有真正提供任何优势,而不是将所有文件保存在硬盘驱动器文件夹中,只是将文件的位置存储在数据库中。 你确定你要这么做吗?
这是Ronnie答案的快速重构:
Public Shared Sub SaveUploadedFile(File As HttpPostedFile)
Dim oFile As Db.File
oFile = New Db.File
oFile.Data = File.ToBytes
End Sub
<Extension()>
Public Function ToBytes(File As HttpPostedFile) As Byte()
ToBytes = New Byte(File.ContentLength - 1) {}
Using oStream As Stream = File.InputStream
oStream.Read(ToBytes, 0, File.ContentLength)
End Using
End Function
HTH
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.