hi everyone. how can i upload image using asp.net with vb.net

Dani AI

Generated

A quick, practical overview that builds on (save to server) and (store in DB): for most web apps serving photos or avatars it’s simpler and faster to save images on disk (or cloud object storage) and store only the path in the database; keep DB storage (or SQL FILESTREAM) for cases that need transactional guarantees, centralized backups, or very large BLOB workflows. (microsoft.com)

Focus on validation and attack-surface reduction: use a whitelist of allowed extensions, never trust client MIME/extension alone, rename files to a server-generated name (GUID), and validate the bytes by loading with an image library (this both confirms format and avoids tricked files). Also serve uploaded files from a location that cannot execute scripts and scan uploads if possible. (cheatsheetseries.owasp.org)

Remember server/IIS limits: increase maxRequestLength (kilobytes) in <httpRuntime> and maxAllowedContentLength (bytes) in <requestFiltering><requestLimits> when you expect larger uploads, and check uploadReadAheadSize if uploads fail at small sizes. If uploads fail silently, look for IIS log substatus codes (413.*, 404.14/404.15) to diagnose. (learn.microsoft.com)

A compact VB.NET pattern (validate, image-check, resize, save with a GUID):

Protected Sub UploadButton_Click(sender As Object, e As EventArgs)
    If Not FileUpload1.HasFile Then Return

    Dim ext = Path.GetExtension(FileUpload1.FileName).ToLowerInvariant()
    Dim allowed = New String() {".jpg",".jpeg",".png",".gif"}
    If Not allowed.Contains(ext) Then
        lblMessage.Text = "Invalid file type"
        Return
    End If

    Try
        Using ms As New MemoryStream(FileUpload1.FileBytes)
            Using img As System.Drawing.Image = System.Drawing.Image.FromStream(ms, False, True)
                ' optional: downscale to max width
                Dim maxW = 1024
                Dim ratio = Math.Min(1.0, maxW / CDbl(img.Width))
                Dim thumb = New Bitmap(img, CInt(img.Width * ratio), CInt(img.Height * ratio))
                Dim saveName = Guid.NewGuid().ToString("N") & ext
                Dim savePath = Server.MapPath("~/uploads/") & saveName
                thumb.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg)
            End Using
        End Using
        lblMessage.Text = "Upload OK"
    Catch ex As Exception
        lblMessage.Text = "Upload failed"
    End Try
End Sub

Quick checklist: create an uploads folder with IIS write but no execute rights; enforce server-side size/type checks; log upload errors (IIS + app) and test changes to web.config/IIS on a staging server before production. See the earlier posts for basic wiring; use the above as a hardened pattern.

Recommended Answers

All 3 Replies

Hi

You can use the FileUpload control to request the file from the user and then use the SaveAs method to save it to the server. That is assuming that you want to save it to disk and not to a database or something else as you haven't really specified much information.

A quick example would be:

ASPX Page

<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="fileUpload" runat="server" />
        <p>
            <asp:Button ID="uploadButton" runat="server" Text="Upload File" OnClick="uploadButton_Click" />
        </p>
    </div>
    </form>
</body>

Code behind

Protected Sub uploadButton_Click(sender As Object, e As EventArgs)

    'Ensure a file was selected before attempting to read it
    If fileUpload.HasFile Then

        Dim file As String = fileUpload.FileName
        fileUpload.SaveAs(String.Format("{0}{1}", Server.MapPath("~/"), file))

    End If

End Sub

HTH

You can upload the image directly to the database too.

Aspx Page

<asp:FileUpload ID=FileUpload1 runat=server ></asp:FileUpload>

<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_Click" ></asp:Button>
<br />
<asp:Label ID="lblMessage" runat="server" Text=""
Font-Names = "Arial"></asp:Label>

VB.Net Code

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
  ' Read the file and convert it to Byte Array
  Dim filePath As String = FileUpload1.PostedFile.FileName
  Dim filename As String = Path.GetFileName(filePath)
  Dim ext As String = Path.GetExtension(filename)
  Dim contenttype As String = String.Empty

  'Set the contenttype based on File Extension
  Select Case ext
    Case ".doc"
      contenttype = "application/vnd.ms-word"
      Exit Select
    Case ".docx"
      contenttype = "application/vnd.ms-word"
      Exit Select
    Case ".xls"
      contenttype = "application/vnd.ms-excel"
      Exit Select
    Case ".xlsx"
      contenttype = "application/vnd.ms-excel"
      Exit Select
    Case ".jpg"
      contenttype = "image/jpg"
      Exit Select
    Case ".png"
      contenttype = "image/png"
      Exit Select
    Case ".gif"
      contenttype = "image/gif"
      Exit Select
    Case ".pdf"
      contenttype = "application/pdf"
      Exit Select
    End Select
    If contenttype <> String.Empty Then
      Dim fs As Stream = FileUpload1.PostedFile.InputStream
      Dim br As New BinaryReader(fs)
      Dim bytes As Byte() = br.ReadBytes(fs.Length)

      'insert the file into database
       Dim strQuery As String = "insert into tblFiles" _
       & "(Name, ContentType, Data)" _
       & " values (@Name, @ContentType, @Data)"
       Dim cmd As New SqlCommand(strQuery)
       cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename
       cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value _
       = contenttype
       cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes
       InsertUpdateData(cmd)
       lblMessage.ForeColor = System.Drawing.Color.Green
       lblMessage.Text = "File Uploaded Successfully"
     Else
       lblMessage.ForeColor = System.Drawing.Color.Red
       lblMessage.Text = "File format not recognised." _
       & " Upload Image/Word/PDF/Excel formats"
     End If
  End Sub



Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
    Dim strConnString As String = System.Configuration.
    ConfigurationManager.ConnectionStrings("conString").ConnectionString
    Dim con As New SqlConnection(strConnString)
    cmd.CommandType = CommandType.Text
    cmd.Connection = con
    Try
      con.Open()
      cmd.ExecuteNonQuery()
      Return True
    Catch ex As Exception
      Response.Write(ex.Message)
      Return False
    Finally
      con.Close()
      con.Dispose()
    End Try
End Function

Database Table

Field
id int
Name varchar(50)
ContentType varchar(50)
Data varbinary(MAX)

thank you very much for reply me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.