[英]what is the best way to store pdf files in sql server from an asp.net mvc 2 application?
I am trying to store pdf files in sql server. 我正在尝试将pdf文件存储在sql服务器中。 I am using an asp.net mvc 2 application with sql server? 我正在使用带有SQL Server的ASP.NET MVC 2应用程序? Can you show me some links to code samples? 您能告诉我一些代码示例链接吗?
The answer will depend very much on what technology you use to access this SQL Server, whether you are using an ORM, etc... Because you haven't provided any such information in your question, let me illustrate an example of how to do this using plain ADO.NET. 答案很大程度上取决于您使用什么技术来访问此SQL Server,是否使用ORM等。由于您的问题中未提供任何此类信息,因此让我举例说明如何执行此操作使用纯ADO.NET。
You could start with a form: 您可以从以下表格开始:
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<label for="file">Select a pdf file:</label>
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" />
<% } %>
and a controller action to handle the submission of this form: 以及处理此表单提交的控制器操作:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var extension = Path.GetExtension(fileName);
var document = new byte[file.InputStream.Length];
file.InputStream.Read(document, 0, document.Length);
if (string.Equals(".pdf", extension, StringComparison.OrdinalIgnoreCase))
{
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "INSERT INTO Documents (document) VALUES (@document);";
cmd.Parameters.Add("@document", SqlDbType.Binary, 20).Value = document;
cmd.ExecuteNonQuery();
}
}
}
return View();
}
Of course the SQL part should be externalized into a separate repository to avoid cluttering the controller action with such code. 当然,应该将SQL部分外部化到一个单独的存储库中,以避免使用此类代码使控制器操作混乱。 Also if you are using SQL Server 2008 you might take a look at the new FILESTREAM type which is more adapted to this sort of things. 另外,如果您使用的是SQL Server 2008,则可以看看新的FILESTREAM类型 ,它更适合这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.