PDF download doesnt work, instead opening unreadable in browser - asp.net

I have an asp.net application which allows user to download PDF files. but instead of downloading it, the browser opens the file with unreadable block characters.
Download Code
Protected Sub btn_dwnd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_dwnd.Click
cn.Open()
cmd.CommandText = "Select * from Syllabus where file_name ='" & txtdwd_file.Text & "'"
cmd.Connection = cn
dr = cmd.ExecuteReader
Do While dr.Read
Response.WriteFile(dr("file_name"))
Loop
cn.Close()
End Sub
I am trying to download my uploaded pdf file in my project's root directory D:\OLMS when I click download unreable characters opens up in browser (square characters). I think it opens up pfd file in browser
Upload Code
Protected Sub btnadd_sylbus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnadd_sylbus.Click
Dim extension As String = System.IO.Path.GetExtension(FileUpload_sylbus.PostedFile.FileName).ToLower()
Dim Type As String = Nothing
If (extension = ".pdf") Then
Dim strFileNamePath As String
Dim strFileNameOnly As String
strFileNamePath = FileUpload_sylbus.PostedFile.FileName
strFileNameOnly = Path.GetFileName(strFileNamePath)
Dim newFileNamePath As String = Path.Combine("D:\OLMS", strFileNameOnly)
Dim br As New BinaryReader(FileUpload_sylbus.PostedFile.InputStream)
FileUpload_sylbus.PostedFile.SaveAs(newFileNamePath)
cmd.CommandText = "INSERT into Syllabus(sylbus_id, sylbus_name, file_name, content) values(#id,#name,#file,#cont)"
cmd.Connection = cn
cmd.Parameters.Add("#id", txtsylbus_id.Text)
cmd.Parameters.Add("#name", txtsylbus_name.Text)
cmd.Parameters.Add("#file", FileUpload_sylbus.FileName)
cmd.Parameters.Add("#cont", br.ReadBytes(FileUpload_sylbus.PostedFile.ContentLength))
cmd.ExecuteNonQuery()
cn.Close()
lbladd_sylbus.Visible = True
lbladd_sylbus.Text = "File Upload Success."
txtsylbus_id.Text = Nothing
txtsylbus_name.Text = Nothing
Else
lbladd_sylbus.Visible = True
lbladd_sylbus.Text = "Not a Valid file format"
End If
End Sub

Thanx guys it worked :D
Response.ClearHeaders()
Response.ClearContent()
Response.ContentType = "application/octet-stream"
Response.Charset = "UTF-8"
Response.AddHeader("content-disposition", "attachment; filename=" & dr("file_name"))
Response.WriteFile("D:\OLMS\" & dr("file_name"))
Response.End()

Related

Running Code After Response.End() and Alternatives for it

I'm exporting code to a csv file and the process terminates with Response.End() as expected and the SendEmail routine in the Finally clause is never executed. I need to run SendEmail() after Response.End and looking for suggestions. If just remove Response.End, then the csv file is never created.
Protected Sub ExportExcel(ByVal Vendor As String)
Dim MyConnection As SqlConnection
MyConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("BusOpsConnectionString").ConnectionString)
Dim cmd As New SqlCommand("p_BPOTracker_ClosedReport", MyConnection)
With cmd
.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Vendor", SqlDbType.VarChar).Value = Vendor
cmd.Parameters.AddWithValue("#IssueStatus", SqlDbType.VarChar).Value = "Closed"
End With
Dim da As New SqlDataAdapter(cmd)
Dim myDataTable As DataTable = New DataTable()
da.Fill(myDataTable)
Dim FileDate As String = Replace(FormatDateTime(Now(), DateFormat.ShortDate), "/", "")
Dim attachmentName As String = "BPOTracker_Closed_Report_" & Vendor & "_" & FileDate & "_.csv"
Try
MyConnection.Open()
Response.Clear()
Response.ClearHeaders()
Dim writer As New CsvWriter(Response.OutputStream, ","c, Encoding.Default)
writer.WriteAll(myDataTable, True)
writer.Close()
Response.AddHeader("Content-Disposition", "attachment;filename=" & attachmentName)
Response.ContentType = "application/vnd.ms-excel"
Response.End()
Finally
If MyConnection.State <> ConnectionState.Closed Then MyConnection.Close()
MyConnection.Dispose()
MyConnection = Nothing
myDataTable.Dispose()
myDataTable = Nothing
Thread.Sleep(3000)
SendEmail(Vendor, attachmentName)
End Try
End Sub
Sub SendEmail(ByVal Vendor As String, ByVal attachmentFileName As String)
'Send Email
End Sub
The root of the issue here is that you don't have a clear way of getting the generated file as an attachment to the file. Your CSVWriter is writing directly to the HTTP Response. Instead you can write to a file location on disk, or to memory. At that point you can send the email with the file as an attachment. Then you can write the file to the response and then end the response.
Your methods could use some more breakdown. I suggest one method for generating the file, one method for sending the file to an email (you've got that one already) and another method for writing the file to the response.

VB.net No Prompt for User Downloads using Response.Flush

I'm attempting to allow a user to download an excel file created in VB.net using Workbook/Worksheet objects. The creation of the excel file is complet but the next is to allow a user to download it when they click a button. I've coded what I believe is the desired method using Response however when I click on the button the download event (tested on Chrome/IE) doesn't happen. It's as if I never pressed the button but it runs through the code during debug.
Protected Sub btnMatrixSummary_Click(sender As Object, e As System.EventArgs) Handles btnMatrixSummary.Click
Dim refNum As Integer = employee_LB.SelectedValue
Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Cells(1, 2) = "1. Displays High Integrity & Honesty"
'----------FILL REST OF EXCEL FILE HERE---------------------
'Prepare download file
Dim folder As String = Path.GetTempPath
xlWorkBook.SaveAs(folder & "Matrix.xlsx")
Dim filePath As System.IO.FileInfo = New System.IO.FileInfo(xlWorkBook.FullName)
xlWorkBook.Close(True, misValue, misValue)
xlApp.Quit()
releaseObject(xlWorkSheet)
releaseObject(xlWorkBook)
releaseObject(xlApp)
Response.ClearHeaders()
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=Matrix6.xls")
Response.AddHeader("Content-Length", filePath.Length.ToString())
Response.ContentType = "application/vnd.xls"
Response.WriteFile(filePath.FullName)
HttpContext.Current.Response.Flush() 'Sends all currently buffered output To the client.
HttpContext.Current.Response.SuppressContent = True 'Gets Or sets a value indicating whether To send HTTP content To the client.
HttpContext.Current.ApplicationInstance.CompleteRequest()
'Delete local matrix off server
My.Computer.FileSystem.DeleteFile(filePath.FullName)

Gridview to .xlsx

Wondering if someone could give me answer and some tip if it's possibly to export a grindview to a .xlsx (2007 versions of excel).
I have manage to transfer the grindview to .xls (2003 excel) but not to xlsx.
my code is:
Regards
Lime3003
Protected Sub ExportToExcel(sender As Object, e As EventArgs)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=" + selReportName + " .xls")
Response.Charset = ""
Response.ContentType = "Application / vnd.openxmlformats - officedocument.spreadsheetml.sheet"
'Response.ContentType = "application/vnd.ms-excel"
Using sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
gwResult.GridLines = GridLines.Both
gwResult.RenderControl(hw)
'style to format numbers to string
Dim style As String = "<style> .textmode { } </style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.[End]()
End Using
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
As Tim Schmelter said I was using EPPlus for export the dataview but I needed to change it to datatable.
Protected Sub ExportToExcel(sender As Object, e As EventArgs)
Dim dt As DataTable
dt = dvData.ToTable
'MsgBox(gwResult.HeaderRow.Cells.Count)
Try
Dim pck = New OfficeOpenXml.ExcelPackage()
Dim ws = pck.Workbook.Worksheets.Add(selReportName)
ws.Cells("A2").LoadFromDataTable(dt, True)
Response.Clear()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=" + selReportName + ".xlsx")
Response.BinaryWrite(pck.GetAsByteArray())
'log error
Catch ex As Exception
End Try
Response.[End]()
End Sub

How to save and retrieve image in SQL Server 2008R2 using Asp.Net via VB.Net

I have a FileUpload fileupload2 control and an image box control image1. Now I want to save the browsing image and also show it on image box when I browsing the path. I am writing the code like below.
What's the problem in that code and how I show it on image box when I browsing the path?
Protected Sub btnsave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsave.Click
Connection()
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "INSERT INTO Personal_info (image_id,pic)VALUES (#image_id,#pic)"
cmd.Parameters.Add("#image_id", SqlDbType.VarChar, 200)
cmd.Parameters.Add("#pic", SqlDbType.Image, 200)
cmd.Parameters("#image_id").Value = txtid.Text
cmd.Parameters("#pic").Value = FileUpload2.FileBytes
Dim i = -1
i = cmd.ExecuteNonQuery
If i = -1 Then
lblMessage.ForeColor = Drawing.Color.Red
lblMessage.Text = "Fail to Save"
'MsgBox("Fail", MsgBoxStyle.OkOnly, "Error")
Else
lblMessage.ForeColor = Drawing.Color.Green
lblMessage.Text = "Success to Save"
End If
End Sub
to show the imange in the image box you need to provide the imange path or url. you cannot read it directly from the database.
one way to do it is to
retrieve the imange from the database
save the image in the server
pass the image box the image server path
'1. retrieve the imange from the database
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "SELECT pic FROM Personal_info WHERE image_id=#image_id;"
cmd.Parameters.Add("#image_id", image_id)
Dim rd As SqlDataReader = cmd.ExecuteReader
Dim MyData() As Byte
If rd.Read Then
If rd("pic").ToString <> Nothing Then
MyData = rd("pic")
End If
End If
'2. save the image in the server
Dim oFileStream As New System.IO.FileStream(System.AppDomain.CurrentDomain.BaseDirectory & "image\image.jpg", System.IO.FileMode.Create, IO.FileAccess.ReadWrite)
oFileStream.Write(MyData, 0, MyData.Length)
oFileStream.Close()
'3. pass the image box the image server path
image1.ImageUrl = "~/image/image.jpg"

upload the file twice in database

I using ASP.net program and SQL database
and I want to upload various files to the database
I used this code to do that, but it does upload the file twice in database
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Partial Class Document
Inherits System.Web.UI.Page
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
'Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection("Data Source=SON\SQLDB;Initial Catalog=myDB;Integrated Security=True")
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
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
' 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 ArchivedFile" _
& "(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
End Class
I do not know what the exact problem is.
I hope someone can help me.
You have the code attached to a button - any chance someone is just double-clicking on the button?
The first thing I would do is determine what part(s) of your code are running twice. Use debugging and breakpoints to determine how many times Sub btnUpload_Click runs, how many times Function InsertUpdateData is called, etc.
Also, from the context of your question I gather the double-insert is happening when you test it, not just in production. Is that accurate?
If that doesn't lead you directly to the cause of the problem, please update your question with the results so we can examine further.
My suspicion is that btnUpload_Click fires twice for some reason, if that turns out to be the case please post the markup for your button, whether it is contained in an UpdatePanel, and any client script that may be applicable.

Resources