After having some problems trying to get my fileupload control to work, I have decided to try it by uploading the file (which is a picture) to a database. Only thing is, I have no idea how to code for this. If anyone knows how to change some of this code below to get the file to upload to a database, I would greatly appreciate your help. Thanks. Code: # Imports System.IO # Imports System.Drawing # Imports System.Web.UI.HtmlControls # Partial Class FileUpload # Inherits System.Web.UI.Page # # Private Const SCRIPT_TEMPLATE As String = "<" + "script " + "type=""text/javascript"">window.parent.photoUploadComplete('{0}', {1});" + "<" + "/script" + ">" # # Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load # Session("UserName") = HttpContext.Current.User.Identity.Name # If IsPostBack Then # Dim UpPath As String # UpPath = "e:\web\XXXXXX\htdocs\Clients\Photos" # If Not Directory.Exists(UpPath) Then # Directory.CreateDirectory("e:\web\XXXXXX\htdocs\Clients\Photos") # End If # 'Sleeping for 10 seconds, fake delay, You should not it try at home. # System.Threading.Thread.Sleep(3000) # UploadPhoto() # End If # End Sub # Private Sub UploadPhoto() # # Dim script As String = String.Empty # # If (filPhoto.PostedFile IsNot Nothing) AndAlso (filPhoto.PostedFile.ContentLength > 0) Then # If Not IsValidImageFile(filPhoto) Then # script = String.Format(SCRIPT_TEMPLATE, "The uploaded file is not a valid image file.", "true") # End If # Else # script = String.Format(SCRIPT_TEMPLATE, "Please specify a valid file.", "true") # End If # # If filPhoto.PostedFile.ContentLength > 150 * 1024 Then # 'resrticting to 150 KB # script = String.Format(SCRIPT_TEMPLATE, "The file is too large. Please limit size to 150 kb.", "true") # End If # # If String.IsNullOrEmpty(script) Then # 'Uploaded file is valid, now we can do whatever we like to do, copying it file system, # 'saving it in db etc. # # Dim strFileName As String # strFileName = filPhoto.PostedFile.FileName # Dim fileExt As String = System.IO.Path.GetExtension(filPhoto.PostedFile.FileName.ToLower()) # Dim c As String = HttpContext.Current.User.Identity.Name # 'Dim c As String = System.IO.Path.GetFileName(strFileName) # Try # filPhoto.PostedFile.SaveAs("e:\web\XXXXXX\htdocs\Clients\Photos" + c + fileExt) # script = String.Format(SCRIPT_TEMPLATE, "File was uploaded. To upload your logo, click Step 2 below.", "false") # Catch exp As Exception # script = String.Format(SCRIPT_TEMPLATE, "File upload FAILED. Please try again.", "false") # # End Try # End If # # 'Now inject the script which will fire when the page is refreshed. # ClientScript.RegisterStartupScript(Me.[GetType](), "uploadNotify", script) # End Sub # # Private Shared Function IsValidImageFile(ByVal file As HtmlInputFile) As Boolean # Try # Using bmp As New Bitmap(file.PostedFile.InputStream) # Return True # End Using # 'throws exception if not valid image # Catch generatedExceptionName As ArgumentException # End Try # # Return False # End Function # # End Class
Hi, I can provide links for this and you can find examples on CodePlex but. . . I'm sure most of us would recommend that you consider NOT doing this. It is much better overall to upload the files to the site and if you want a DB list store the file and path in the DB. That way the file is a lighter resource and you will still have a DB record. Are you simply looking for some ASP.NET code for uploading images? We can help. All the best, Mark
I'm not sure what I need to be honest. The code I listed above works perfectly on my local machine (obviously after changing the path) but It won't work for using it on my hosting account. I have contacted support and sent them my code, but they said they can't help me and to post my request here. If you have some sample code, that would be great. I like the code I have been using though, because it offers a progress bar for the upload. ANY suggestions you have would be greatly appreciated. This thing has been frustrating to get working.
Hi, Here are some links to help. The first one below is really cool. http://www.c-sharpcorner.com/Upload...oad05122009042335AM/MultipleImagesUpload.aspx http://rufan-redi.blogspot.com/2005/09/upload-and-resize-image-with-aspnet.html http://www.codeproject.com/KB/aspnet/simpleuploadimage.aspx http://forums.asp.net/t/1085119.aspx All the best, Mark
Hi This code is useful to upload image Image SQL CREATE TABLE [dbo].[image] ( [img_pk] [int] IDENTITY (1, 1) NOT NULL , [img_name] [varchar] (50) NULL , [img_data] [image] NULL , [img_contenttype] [varchar] (50) NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER TABLE [dbo].[image] WITH NOCHECK ADD CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED ( [img_pk] ) ON [PRIMARY] GO UploadImage.aspx <%@ Page language="c#" Src="UploadImage.aspx.cs" Inherits="DBImages.UploadImage" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> </HEAD> <body bgcolor=#ffffff> <form enctype="multipart/form-data" runat=server id=form1 name=form1> <h3>The ASPFree Friendly Image Uploader</h3> Enter A Friendly Name<input type=text id=txtImgName runat="server" > <asp:RequiredFieldValidator id=RequiredFieldValidator1 runat="server" ErrorMessage="Required" ControlToValidate="txtImgName"></asp:RequiredFieldValidator> <br>Select File To Upload: <input id="UploadFile" type=file runat=server> <asp:button id=UploadBtn Text="Upload Me!" OnClick="UploadBtn_Click" runat="server"></asp:button> </form> </body> </HTML> UploadImage.aspx.cs ( codebehind file) using System; using System.Configuration; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.IO; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace DBImages { public class UploadImage : System.Web.UI.Page { protected System.Web.UI.WebControls.Button UploadBtn; protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.HtmlControls.HtmlInputText txtImgName; protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile; public UploadImage() { } private void Page_Load(object sender, System.EventArgs e){ } public void UploadBtn_Click(object sender, System.EventArgs e) { if (Page.IsValid) //save the image { Stream imgStream = UploadFile.PostedFile.InputStream; int imgLen = UploadFile.PostedFile.ContentLength; string imgContentType = UploadFile.PostedFile.ContentType; string imgName = txtImgName.Value; byte[] imgBinaryData = new byte[imgLen]; int n = imgStream.Read(imgBinaryData,0,imgLen); int RowsAffected = SaveToDB( imgName, imgBinaryData,imgContentType); if ( RowsAffected>0 ) { Response.Write("<BR>The Image was saved"); } else { Response.Write("<BR>An error occurred uploading the image"); } } } private int SaveToDB(string imgName, byte[] imgbin, string imgcontenttype) { //use the web.config to store the connection string SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]); SqlCommand command = new SqlCommand( "INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( @img_name, @img_data,@img_contenttype )", connection ); SqlParameter param0 = new SqlParameter( "@img_name", SqlDbType.VarChar,50 ); param0.Value = imgName; command.Parameters.Add( param0 ); SqlParameter param1 = new SqlParameter( "@img_data", SqlDbType.Image ); param1.Value = imgbin; command.Parameters.Add( param1 ); SqlParameter param2 = new SqlParameter( "@img_contenttype", SqlDbType.VarChar,50 ); param2.Value = imgcontenttype; command.Parameters.Add( param2 ); connection.Open(); int numRowsAffected = command.ExecuteNonQuery(); connection.Close(); return numRowsAffected; } } } Web.Config <configuration> <appSettings> <add key="DSN" value="server=localhost;uid=sa;pwd=;Database=aspfree"/> </appSettings> <system.web> <customErrors mode="Off" /> </system.web> </configuration>