How to upload / store images in ASP
By Guest |
Nov 10, 2021 |
ASP NET
How to upload or insert image in ASP.NET
We will be storing the image name and the path in the database and moving the image file in a folder called "uploads".
We will use the "FileUpload" tool from the toolbox to upload the image.
<form id="form1" runat="server">
<div>
<label>Upload Product Image</label>
<asp:FileUpload ID="p_image" Required="True" class="form-control" runat="server" />
</div>
<asp:Button ID="addProductBtn" runat="server" class="btn btn-primary" Text="Save Product" />
</form>
We will fetch the image in the code behind on button click action, when the user clicks the submit button.
We have to create a folder and name it as "uploads" and move the uploaded images to that folder using below code:
Protected Sub addProductBtn_Click(sender As Object, e As EventArgs) Handles addProductBtn.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim path As String
con.ConnectionString = "YOUR_CONNECTION_STRING_HERE"
con.Open()
cmd.Connection = con
If p_image.HasFile Then
path = p_image.FileName
p_image.SaveAs(Server.MapPath("uploads/") + path)
path = "uploads/" + path
Else
Response.Write("NO FILE SELECTED")
End If
con.Close()
con.Open()
cmd = New SqlCommand("INSERT INTO products (image) values('" & path & "')", con)
cmd.ExecuteNonQuery()
MsgBox("Product added successfully", MsgBoxStyle.Information, "Success")
con.Close()
End Sub