简体   繁体   中英

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. I am using an asp.net mvc 2 application with sql server? 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM