Upload default image if no image is selected

Baiju EP 141 Reputation points
2023-05-24T14:00:03.2533333+00:00

In my asp.net+VB+SQL web i have a page to upload image to sql table. I had attached teh code in text file as i was getting error while adding the code in this page.4

I am able to insert new image with this code. but i want to add a default image if user had not browsed and added image.

Developer technologies ASP.NET Other
{count} votes

1 answer

Sort by: Most helpful
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2023-06-22T05:14:02.98+00:00

    Hi @Baiju EP,

    I had attached teh code in text file as i was getting error while adding the code in this page.

    Your text file is not provided, you'd better provide error message and code.

    I wrote an example according to your needs, you can refer to it.

    First you need to add a default image and name it as Default.png and place it in your project.

    Then you can make a judgment, when FileUpload has no files, upload the default picture.

            Dim bytes As Byte() = Nothing
            If Me.FileUpload1.HasFile Then
                ....
            Else
                filename = "Default.png"
                contenttype = "image/png"
                Dim defaultImage As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath("~/Default.png"))
    
                Using ms As MemoryStream = New MemoryStream()
                    defaultImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
                    bytes = ms.ToArray()
                End Using
            End If
    

    All Code

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
    <br />
    <asp:Label ID="lblMessage" runat="server" Text="" Font-Names="Arial"></asp:Label>
    <hr />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="Id" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:TemplateField HeaderText="Image">
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" ImageUrl='<%# ToBase64(Eval("Data")) %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    
     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Me.IsPostBack Then
                Me.GridView1.DataSource = GetData("SELECT Id, Name, Data FROM tblFiles")
                Me.GridView1.DataBind()
            End If
        End Sub
        Protected Function ToBase64(ByVal data As Object) As String
            Dim bytes As Byte() = CType(data, Byte())
            Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
            Return "data:image/png;base64," & base64String
        End Function
    
        Private Function GetData(ByVal query As String) As DataTable
            Dim dt As DataTable = New DataTable()
            Dim constr As String = ConfigurationManager.ConnectionStrings("DBCS").ConnectionString
    
            Using con As SqlConnection = New SqlConnection(constr)
    
                Using cmd As SqlCommand = New SqlCommand(query)
    
                    Using sda As SqlDataAdapter = New SqlDataAdapter()
                        cmd.CommandType = CommandType.Text
                        cmd.Connection = con
                        sda.SelectCommand = cmd
                        sda.Fill(dt)
                    End Using
                End Using
    
                Return dt
            End Using
        End Function
    
        Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
            Dim filePath As String = String.Empty
            Dim contenttype As String = String.Empty
            Dim filename As String = String.Empty
            Dim bytes As Byte() = Nothing
    
            If Me.FileUpload1.HasFile Then
                filePath = FileUpload1.PostedFile.FileName
                filename = Path.GetFileName(filePath)
                Dim ext As String = Path.GetExtension(filename)
                contenttype = String.Empty
    
                Select Case ext
                    Case ".jpg"
                        contenttype = "image/jpg"
                    Case ".png"
                        contenttype = "image/png"
                    Case ".gif"
                        contenttype = "image/gif"
                End Select
    
                Using fs As Stream = FileUpload1.PostedFile.InputStream
    
                    Using br As BinaryReader = New BinaryReader(fs)
                        bytes = br.ReadBytes(CType(fs.Length, Int32))
                    End Using
                End Using
            Else
                filename = "Default.png"
                contenttype = "image/png"
                Dim defaultImage As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath("~/Default.png"))
    
                Using ms As MemoryStream = New MemoryStream()
                    defaultImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
                    bytes = ms.ToArray()
                End Using
            End If
    
            Dim query As String = "INSERT INTO tblFiles(Id,Name, ContentType, Data) VALUES (@Id,@Name, @ContentType, @Data)"
            Dim constr As String = ConfigurationManager.ConnectionStrings("DBCS").ConnectionString
    
            Using con As SqlConnection = New SqlConnection(constr)
    
                Using cmd As SqlCommand = New SqlCommand(query)
                    cmd.Parameters.Add("@Id", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text)
                    cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename
                    cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype
                    cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes
                    cmd.CommandType = CommandType.Text
                    cmd.Connection = con
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using
            End Using
    
            lblMessage.ForeColor = Color.Green
            lblMessage.Text = "File Uploaded Successfully"
            Response.Redirect(Request.Url.AbsoluteUri)
        End Sub
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.