SQL Server Provider

SQL Server Provider

Configure AjaxUploader to store uploaded files in SQL Server instead of the file system. Files are stored as binary data in a database table, making them easy to manage and back up with your database. Configure via web.config connection strings and appSettings.

Drag & drop files here, or paste from clipboard
<%-- web.config: connection string and provider settings --%>
<connectionStrings>
    <add name="UploadDb"
         connectionString="Server=.;Database=MyApp;Trusted_Connection=true;"
         providerName="System.Data.SqlClient" />
</connectionStrings>

<appSettings>
    <add key="AjaxUploader:StorageProvider" value="SqlServer" />
    <add key="AjaxUploader:ConnectionStringName" value="UploadDb" />
    <add key="AjaxUploader:TableName" value="UploadedFiles" />
    <add key="AjaxUploader:SchemaName" value="dbo" />
    <add key="AjaxUploader:AutoCreateTable" value="true" />
</appSettings>

<%-- The provider automatically creates a table like: --%>
-- CREATE TABLE [dbo].[UploadedFiles] (
--     [Id]          UNIQUEIDENTIFIER PRIMARY KEY,
--     [FileName]    NVARCHAR(256),
--     [ContentType] NVARCHAR(128),
--     [FileSize]    BIGINT,
--     [FileData]    VARBINARY(MAX),
--     [CreatedAt]   DATETIME2 DEFAULT GETUTCDATE()
-- );

<%-- Retrieve a file from SQL Server in an .ashx handler --%>
public class FileHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        Guid id = Guid.Parse(context.Request.QueryString["id"]);
        string connStr = ConfigurationManager
            .ConnectionStrings["UploadDb"].ConnectionString;

        using (var conn = new SqlConnection(connStr))
        using (var cmd = new SqlCommand(
            "SELECT FileName, ContentType, FileData " +
            "FROM UploadedFiles WHERE Id = @Id", conn))
        {
            cmd.Parameters.AddWithValue("@Id", id);
            conn.Open();
            using (var reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    context.Response.ContentType =
                        reader["ContentType"].ToString();
                    context.Response.BinaryWrite(
                        (byte[])reader["FileData"]);
                }
            }
        }
    }
}