Home » Asp.netRSS

File Upload to Database

Hi All

I'm using a DetailsView control and have a FileUpload control in a TemplateField for uploading images to a database.

However, I'm not sure how to take the image name e.g. Button.png as a value and enter it into the database.

Thanks for your help.

 

6 Answers Found

 

Answer 1

I probably should add that I'm not trying to upload binary data, I just want to upload the file and save the file name in the db.


Thx

 

Answer 2

Try FileUpload1.PostedFile.FileName

 

Answer 3

Sorry, I'm not sure how to integrate that (Newb alert!). Currently, I have this:

<EditItemTemplate>

<asp:ImageID="Image1"ImageUrl='<%# Bind("MenuThumbImage") %>'runat="server"/>  

<asp:FileUploadID="FileUpload1"runat="server"/>

<asp:TextBoxID="TextBox1"runat="server"Text='<%# Bind("MenuThumbImage") %>'></asp:TextBox>  

</EditItemTemplate>

 

How would I add your bit?

Thx

 

Answer 4

How do you upload your file right now? You should have an event somewhere where you save the file at the file system. Then you need to update database with the name of the file. You can find some code examples here.

 

Answer 5

In fact, you can easily store image into db and retireve it with the help of HttpHander. Here's some snippets of codes:

Your webpage's markups:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CSImageEditUpload._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Personal Information</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>
            OverView of Persons</h2>
        <asp:SqlDataSource ID="SqlDSPersonOverView" runat="server"
            ConnectionString="<%$ ConnectionStrings:db_PersonsConnectionString %>"
            SelectCommand="SELECT [Id], [PersonName] FROM [tb_personInfo]">
        </asp:SqlDataSource>
        <asp:GridView ID="gvPersonOverView" runat="server" CellPadding="4" EnableModelValidation="True"
            ForeColor="#333333" GridLines="None" Width="70%" AutoGenerateColumns="False"
            DataKeyNames="Id" DataSourceID="SqlDSPersonOverView"
            onselectedindexchanged="gvPersonOverView_SelectedIndexChanged"
            AllowPaging="True" AllowSorting="True">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True"
                    SortExpression="Id" />
                <asp:BoundField DataField="PersonName" HeaderText="PersonName" SortExpression="PersonName" />
                <asp:CommandField ShowSelectButton="True" HeaderText="Click to see Details" SelectText="Details..." />
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <EmptyDataTemplate>
                No Data Available, Please Insert data with the help of the FormView...<br />
            </EmptyDataTemplate>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" VerticalAlign="Middle" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        </asp:GridView>
    </div>
    <h2>
        Person In Detail</h2>
    <asp:FormView ID="fvPersonDetails" runat="server" Width="50%"
        DataSourceID="SqlDSPersonDetails" EnableModelValidation="True" DataKeyNames="Id"
        DataMember="DefaultView" OnItemInserting="fvPersonDetails_ItemInserting"
        onitemupdating="fvPersonDetails_ItemUpdating" BackColor="#DEBA84"
        BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
        CellSpacing="2" GridLines="Both"
        onitemupdated="fvPersonDetails_ItemUpdated"
        onitemdeleted="fvPersonDetails_ItemDeleted"
        onitemdeleting="fvPersonDetails_ItemDeleting"
        oniteminserted="fvPersonDetails_ItemInserted"
        onmodechanging="fvPersonDetails_ModeChanging">
        <ItemTemplate>
            <table width="100%">
                <tr>
                    <th>
                        Person Name:
                    </th>
                    <td colspan="2">
                        <%#Eval("PersonName") %>
                    </td>
                </tr>
                <tr>
                    <th>
                        Person Image:
                    </th>
                    <td colspan="2">
                        <img src='ImageHandler/ImageHandler.ashx?id=<%#Eval("Id") %>' width="200" alt=""
                            height="200" />
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit" Text="Edit" />
                    </td>
                    <td align="center">
                        <asp:LinkButton ID="lnkDelete" runat="server" CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure to delete it completely?');" />
                    </td>
                    <td align="center">
                        <asp:LinkButton ID="lnkNew" runat="server" CommandName="New" Text="New" />
                    </td>
                </tr>
            </table>
        </ItemTemplate>
        <EditItemTemplate>
            <table width="100%">
                <tr>
                    <th>
                        Person Name:
                    </th>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" Text=' <%#Bind("PersonName") %>' MaxLength="20" />
                        <asp:RequiredFieldValidator ID="reqName" runat="server"
                            ControlToValidate="txtName" ErrorMessage="Name is required!">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <th>
                        Person Image:
                    </th>
                    <td>
                        <asp:FileUpload ID="fupEditImage" runat="server" />
                        <asp:CustomValidator ID="cmvImageType" runat="server"
                            ControlToValidate="fupEditImage" ErrorMessage="File is invalid!"
                            OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" Text="Update" />
                    </td>
                    <td align="center">
                        <asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel"
                            Text="Cancel" CausesValidation="False" />
                    </td>
                </tr>
            </table>
        </EditItemTemplate>
        <EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
        <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
        <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
        <InsertItemTemplate>
            <table width="100%">
                <tr>
                    <th>
                        Person Name:
                    </th>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" MaxLength="20" Text='<%#Bind("PersonName") %>'></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
                            ErrorMessage="Name is required!">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <th>
                        Person Image:
                    </th>
                    <td>
                        <asp:FileUpload ID="fupInsertImage" runat="server" />
                        <asp:CustomValidator ID="cmvImageType" runat="server" ControlToValidate="fupInsertImage"
                            ErrorMessage="File is invalid!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <asp:LinkButton ID="lnkInsert" runat="server" CommandName="Insert" Text="Insert" />
                    </td>
                    <td align="center">
                        <asp:LinkButton ID="lnkInsertCancel" runat="server" CommandName="Cancel"
                            Text="Cancel" CausesValidation="False" />
                    </td>
                </tr>
            </table>
        </InsertItemTemplate>
        <PagerStyle HorizontalAlign="Center" ForeColor="#8C4510" />
        <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
    </asp:FormView>
    <asp:SqlDataSource ID="SqlDSPersonDetails" runat="server" ConnectionString="<%$ ConnectionStrings:db_PersonsConnectionString %>"
        DeleteCommand="DELETE FROM tb_personInfo WHERE (Id = @Id)" InsertCommand="INSERT INTO tb_personInfo(PersonName, PersonImage, PersonImageType) VALUES (@PersonName, @PersonImage, @PersonImageType)"
       
        SelectCommand="SELECT [Id], [PersonName] FROM [tb_personInfo] where id=@id"
       
       
        UpdateCommand="UPDATE tb_personInfo SET PersonName = @PersonName, PersonImage = @PersonImage, PersonImageType = @PersonImageType WHERE (Id = @Id)">
        <DeleteParameters>
            <asp:Parameter Name="Id" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="PersonName" Type="String" />
            <asp:Parameter Name="PersonImage" DbType="Binary" ConvertEmptyStringToNull="true" />
            <asp:Parameter Name="PersonImageType" Type="String" ConvertEmptyStringToNull="true" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="PersonName" Type="String" />
            <asp:Parameter Name="PersonImage" DbType="Binary" ConvertEmptyStringToNull="true" />
            <asp:Parameter Name="PersonImageType" Type="String" ConvertEmptyStringToNull="true" />
            <asp:Parameter Name="Id" Type="Int32" />
        </UpdateParameters>
        <SelectParameters>
            <asp:ControlParameter Name="id" Type="Int32" ControlID="gvPersonOverView" PropertyName="SelectedValue" DefaultValue="0" />
        </SelectParameters>
    </asp:SqlDataSource>
   
    </form>
</body>
</html>

You want to make an ImageHttpHandler:

/****************************** ImageHandler Header ******************************\
* Module Name:    ImageHandler.ashx
* Project:        CSImageEditUpload
* Copyright (c) Microsoft Corporation
*
* This is a common http-handler to read out byte collection
* from certain database according to the specific Id record.
*
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
* All other rights reserved.
\*****************************************************************************/

using System;
using System.Collections.Generic;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace CSImageEditUpload.ImageHandler
{
    /// <summary>
    /// Connected to the DataBase,
    /// If the specific record has image,read out the specific row's
    /// image byte collection as well as image type, output it.
    /// If not, output the default image instead.
    /// </summary>
    public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = new SqlConnection(
                    ConfigurationManager.ConnectionStrings["db_PersonsConnectionString"]
                    .ConnectionString);
                cmd.Connection.Open();
                cmd.CommandText = "select PersonImage,PersonImageType from tb_personInfo"+
               " where id=" + context.Request.QueryString["id"];
               
                SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection
                    | System.Data.CommandBehavior.SingleRow);

                if (reader.Read())
                {
                    byte[] imgbytes=null;
                    string imgtype=null;

                    if (reader.GetValue(0) != DBNull.Value)
                    {
                       imgbytes = (byte[])reader.GetValue(0);
                       imgtype = reader.GetString(1);

                        // If bmp, convert to jpg and show because of the different formation type.

                        if (imgtype.Equals("image/bmp",StringComparison.OrdinalIgnoreCase))
                        {
                            using (MemoryStream ms = new MemoryStream(imgbytes))
                            {
                                using (Bitmap bm = new Bitmap(Image.FromStream(ms)))
                                {
                                    bm.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                                }
                            }
                        }
                        else
                        {
                            context.Response.ContentType = imgtype;
                            context.Response.BinaryWrite(imgbytes);
                        }
                       
                    }
                    else
                    {
                        imgbytes = File.ReadAllBytes(context.Server.MapPath
                            ("~/DefaultImage/DefaultImage.JPG"));
                        imgtype = "image/pjpeg";
                        context.Response.ContentType = imgtype;
                        context.Response.BinaryWrite(imgbytes);
                    }
                }
                reader.Close();
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

At last, your cs file codes:

/****************************** Module Header ******************************\
* Module Name:    Default.aspx.cs
* Project:        CSImageEditUpload
* Copyright (c) Microsoft Corporation
*
* The project shows up how to insert,edit or update an image and store
* it into Sql database.
*
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
* All other rights reserved.
\*****************************************************************************/

using System.Collections.Generic;
using System.Web.UI.WebControls;
using System;
using System.Data.SqlClient;
using System.IO;

namespace CSImageEditUpload
{
    public partial class _Default : System.Web.UI.Page
    {
        // Static types of common images for checking.
        private static List<string> imgytpes = new List<string>()
        {
            ".bmp",".BMP",".gif",".GIF",".jpg",".JPG",".png",".PNG"
        };

        /// <summary>
        /// Read all records into GridView.
        /// If has records, select the first record to be shown in the FormView
        /// as default; otherwise, change the formview to insert mode so as to let
        /// data to be inserted.
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gvPersonOverView.DataBind();
       
                if (gvPersonOverView.Rows.Count > 0)
                {
                    gvPersonOverView.SelectedIndex = 0;
                    fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                    fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
                }
                else
                {
                    fvPersonDetails.ChangeMode(FormViewMode.Insert);
                    fvPersonDetails.DefaultMode = FormViewMode.Insert;
                }
            }
        }


        /// <summary>
        /// Validate whether data satisfies the type of image.
        /// </summary>
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (args.Value != null && args.Value != "")
            {
                args.IsValid = imgytpes.IndexOf(System.IO.Path.GetExtension(args.Value)) >= 0;
            }

        }

        /// <summary>
        /// After checking the validation of the image type,
        /// assign the image type and the image byte collection through
        /// the e.Values argument and do the insert.
        /// </summary>
        protected void fvPersonDetails_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            object obj = Session["insertstate"];

            if (obj == null || (bool)obj)
            {
                CustomValidator cv = fvPersonDetails.FindControl("cmvImageType") as CustomValidator;

                cv.Validate();
                e.Cancel = !cv.IsValid;

                FileUpload fup = (FileUpload)fvPersonDetails.FindControl("fupInsertImage");

                if (cv.IsValid && fup.PostedFile.FileName.Trim() != "")
                {
                    e.Values["PersonImage"] = File.ReadAllBytes(fup.PostedFile.FileName);
                    e.Values["PersonImageType"] = fup.PostedFile.ContentType;
                }

            }
            else
            {
                e.Cancel = true;
                gvPersonOverView.DataBind();
                fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
            }
        }

        /// <summary>
        /// After checking the validation of the image type,
        /// assign the image type and the image byte collection through
        /// the e.Values argument and do the update.
        /// </summary>
        protected void fvPersonDetails_ItemUpdating(object sender, FormViewUpdateEventArgs e)
        {
            CustomValidator cv = fvPersonDetails.FindControl("cmvImageType") as CustomValidator;

            cv.Validate();
            e.Cancel = !cv.IsValid;

            FileUpload fup = (FileUpload)fvPersonDetails.FindControl("fupEditImage");

            if (cv.IsValid && fup.PostedFile.FileName.Trim() != "")
            {
                e.NewValues["PersonImage"] = File.ReadAllBytes(fup.PostedFile.FileName);
                e.NewValues["PersonImageType"] = fup.PostedFile.ContentType;
            }
        }

        /// <summary>
        /// After updated, re-databind data and select the first one as default.
        /// </summary>
        protected void fvPersonDetails_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
        {
            gvPersonOverView.DataBind();
            gvPersonOverView.SelectedIndex = gvPersonOverView.SelectedRow.RowIndex;
        }

        /// <summary>
        /// After inserted successfully, re-databind data,select the first one as default,
        /// Change the FormView mode to ReadOnly (for viewing).
        /// </summary>
        protected void fvPersonDetails_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            gvPersonOverView.DataBind();
            gvPersonOverView.SelectedIndex = gvPersonOverView.Rows.Count - 1;
            fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
            fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
        }

        /// <summary>
        /// After deleted successfully, re-databind data.
        /// </summary>
        protected void fvPersonDetails_ItemDeleted(object sender, FormViewDeletedEventArgs e)
        {
            gvPersonOverView.DataBind();

            // If still has records
            if (gvPersonOverView.Rows.Count > 0)
            {
                // Take out the index of row to be deleted
                int delindex = (int)ViewState["delindex"];

                // If the first record is deleted,Move to its next record.
                if (delindex == 0)
                {
                    gvPersonOverView.SelectedIndex = 0;
                }
               
                // If the last record is deleted, Move to its previous one.
                else if (delindex == gvPersonOverView.Rows.Count)
                {
                    gvPersonOverView.SelectedIndex = gvPersonOverView.Rows.Count - 1;
                }

                // Otherwise, move to the next record after itself is deleted.
                else
                {
                    gvPersonOverView.SelectedIndex = delindex;
                }

            }

            // If has no records, change to insert mode for insering new records.
            else
            {
                fvPersonDetails.ChangeMode(FormViewMode.Insert);
                fvPersonDetails.DefaultMode = FormViewMode.Insert;
            }
        }

        /// <summary>
        /// To show detail image and information in the FormView when GridView's
        /// SelectedRowIndex Changed.
        /// </summary>
        protected void gvPersonOverView_SelectedIndexChanged(object sender, EventArgs e)
        {
            fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
            fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
        }

        /// <summary>
        /// Keep the row index into ViewState for the usage of Item_Deleted.
        /// </summary>
        protected void fvPersonDetails_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {
            ViewState["delindex"] = gvPersonOverView.SelectedIndex;
        }

        /// <summary>
        /// Keep the insertState into Session to avoid the duplicated inserting
        /// after refreshing page.
        /// </summary>
        protected void fvPersonDetails_ModeChanging(object sender, FormViewModeEventArgs e)
        {
            Session["insertstate"] = (e.NewMode == FormViewMode.Insert);
        }


    }
}

If you are very interested in my codes (I'm going to post it to CodeFX for released version sample, and it's passed). I'd like to send you with email.

But please leave your email soon or send to maledong@qq.com for my codes (with the title "ImageHander Wanted").

 

Answer 6

Hi

This is my code - it doesn't like the 2nd  half, throwing me a WithEvents error when within the DetailsView control...

Partial

ClassHelicopterDetails

 

Inherits System.Web.UI.Page

 

 

ProtectedSub Page_Load(ByVal sender AsObject, ByVal e As System.EventArgs) HandlesMe.LoadDim UpPath AsString

 

Dim UpName AsString

UpPath =

"C:\UploadedUserFiles"

UpName = Dir(UpPath, vbDirectory)

 

If (UpName = "") Then

MkDir(

 

"C:\UploadedUserFiles")EndIf

 

EndSub

 

FileName.InnerHtml = FileField.PostedFile.FileName

FileContent.InnerHtml = FileField.PostedFile.ContentType

FileSize.InnerHtml = FileField.PostedFile.ContentLength

UploadDetails.Visible =

ProtectedSub UploadButton_Click(ByVal sender AsObject, ByVal e As System.EventArgs) Handles UploadButton.ClickTrue

 

Dim myFileName AsString

myFileName = FileField.PostedFile.FileName

 

 

Dim c AsString = System.IO.Path.GetFileName(myFileName)Try

FileField.PostedFile.SaveAs(

Span1.InnerHtml =

"C:\UploadedUserFiles\" + c)"File Upload Succeeded"

 

Catch ex AsException

Span1.InnerHtml =

"File Upload Failed"

UploadDetails.Visible =

False

 

EndTry

 

End

EndSubClass

Thanks for your help!

 

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter