Sunday

ASP.NET uploading files directly to a SQL database in C#

asp-page-source
 <form id="form1" runat="server">
Please upload file:<br />
<asp:Literal ID="lit_Status" runat="server" /><br />
<b>Name:</b>
<asp:TextBox ID="FileName" runat="server" />
<br />
<b>File:</b>
<asp:FileUpload ID="FileToUpload" runat="server" />
<br />
<asp:Button ID="btn_Upload" runat="server" Text="Upload" onclick="btn_Upload_Click" />
</form>


Code-behind source
 using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btn_Upload_Click(object sender, EventArgs e)
{
if (FileToUpload.PostedFile == null || String.IsNullOrEmpty(FileToUpload.PostedFile.FileName) || FileToUpload.PostedFile.InputStream == null)
{
lit_Status.Text = "
Error - unable to upload file. Please try again.
";
}
else
{
using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
try
{
const string SQL = "INSERT INTO [BinaryTable] ([FileName], [DateTimeUploaded], [MIME], [BinaryData]) VALUES (@FileName, @DateTimeUploaded, @MIME, @BinaryData)";
SqlCommand cmd = new SqlCommand(SQL, Conn);
cmd.Parameters.AddWithValue("@FileName", FileName.Text.Trim());
cmd.Parameters.AddWithValue("@MIME", FileToUpload.PostedFile.ContentType);

byte[] imageBytes = new byte[FileToUpload.PostedFile.InputStream.Length + 1];
FileToUpload.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
cmd.Parameters.AddWithValue("@BinaryData", imageBytes);
cmd.Parameters.AddWithValue("@DateTimeUploaded", DateTime.Now);

Conn.Open();
cmd.ExecuteNonQuery();
lit_Status.Text = "
File successfully uploaded - thank you.
";
Conn.Close();
}
catch
{
Conn.Close();
}
}
}
}
}



more...

No comments:

imagemagic add text to image

rem different types of text annotations on existing images rem cyan yellow orange gold rem -gravity SouthWest rem draw text and anno...