I am trying to have a dynamically created csv file be the response to a page request. I have the code to create a file that can be downloaded by the client, but that isn't the solution. I have found code that can stream a file but the file seems to have to exist on the file system and I would rather not have to use a temp file if I can help it.
Here is what i have:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim csvTable As DataTable = pointsTable_Select_By_playerName_for_CSV()
Dim sb = New StringBuilder
For Each dcol As DataColumn In csvTable.Columns
sb.Append(dcol.ColumnName & ",")
Next
sb.Append(ControlChars.NewLine)
For Each drow As DataRow In csvTable.Rows
For i As Integer = 0 To csvTable.Columns.Count - 1
sb.Append(drow.Item(i).ToString & ",")
Next
sb.Append(ControlChars.NewLine)
Next
Response.Clear()
Response.ContentType = "text/csv"
Response.AppendHeader("Content-Disposition",
String.Format("attachment; filename={0}.csv", DateTime.Now))
Response.Write(sb.ToString)
Context.Response.End()
End Sub
And the code I found to stream a file:
'Create a stream for the file
Dim stream As Stream = Nothing
'This controls how many bytes to read at a time and send to the client
Dim bytesToRead As Integer = 10000
' Buffer to read bytes in chunk size specified above
Dim buffer As Byte() = New [Byte](bytesToRead - 1) {}
' The number of bytes read
Try
'Create a WebRequest to get the file
Dim fileReq As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
'Create a response for this request
Dim fileResp As HttpWebResponse = DirectCast(fileReq.GetResponse(), HttpWebResponse)
If fileReq.ContentLength > 0 Then
fileResp.ContentLength = fileReq.ContentLength
End If
'Get the Stream returned from the response
stream = fileResp.GetResponseStream()
' prepare the response to the client. resp is the client Response
Dim resp = HttpContext.Current.Response
'Indicate the type of data being sent
resp.ContentType = "application/octet-stream"
'Name the file
resp.AddHeader("Content-Disposition", String.Format("attachment; filename={0}.csv", DateTime.Now))
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString())
Dim length As Integer
Do
' Verify that the client is connected.
If resp.IsClientConnected Then
' Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead)
' and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length)
' Flush the data
resp.Flush()
'Clear the buffer
buffer = New [Byte](bytesToRead - 1) {}
Else
' cancel the download if client has disconnected
length = -1
End If
'Repeat until no data is read
Loop While length > 0
Finally
If stream IsNot Nothing Then
'Close the input stream
stream.Close()
End If
End Try
The problem is that this code needs to point to a file, is there a way I can use a stream to move the string from sb to the httpresponse?
You can use use Response.Write().
Additionally, If your data might contain , you should be escaping it by placing inside a text qualifier like ".
You also can not use Date Time as the File Name unless you remove special characters from it.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim FileName As String = (From C In DateTime.Now.ToString()
Where Char.IsLetterOrDigit(C)) & ".csv"
Response.Clear()
Response.ContentType = "text/csv"
Response.AppendHeader("Content-Disposition",
String.Format("attachment; filename={0}.csv", filename)
Dim csvTable As DataTable = pointsTable_Select_By_playerName_for_CSV()
For Each dcol As DataColumn In csvTable.Columns
Response.Write(dcol.ColumnName & ",")
Next
Response.Write(ControlChars.NewLine)
For Each drow As DataRow In csvTable.Rows
Response.Write(String.Join(",", row.ItemArray()) & VbNewLine)
Next
Response.End()
End Sub
Related
I'm trying to generate a PDF using Winnovative Tools. In my click handler which fires after clicking on the "Print PDF button", I have the code below.
I expect control to resume to the printPDF_Click sub routine after calling Server.Execute() but instead it calls the printPDF_Click sub routine from scratch which causes a loop because Server.Execute() will be called again and so on.
It works as expected when I set preserveForm as False but then I lose my form data and the point is retaining it.
Private Sub printPDF_Click(sender As Object, e As EventArgs) Handles printPDF.Click
Dim outTextWriter As IO.TextWriter = New IO.StringWriter()
Server.Execute("Default_v3.aspx?isWinnovative=true", outTextWriter)
Dim baseUrl As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim htmlStringToConvert As String = outTextWriter.ToString()
Dim downloadBytes As Byte() = PdfHelper.CreatePdf(htmlStringToConvert, baseUrl)
Dim response As HttpResponse = HttpContext.Current.Response
response.Clear()
response.AddHeader("Content-Type", "binary/octet-stream")
response.AddHeader("Content-Disposition", ("attachment; filename=" + (
"Rendered.pdf" + ("; size=" + downloadBytes.Length.ToString))))
response.Flush()
response.BinaryWrite(downloadBytes)
response.Flush()
response.End()
End Sub
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)
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()
The code I'm troubleshooting exports a Crystal Report ReportDocument to Excel. Most of the time, the export works just fine. Unfortunately for some datasets, the ExportToHttpResponse method never returns and causes the app to hang. Eventually there is a Thread was being aborted exception along with a request timeout.
Here is the line that hangs:
reportDocument.ExportToHttpResponse(ExportFormatType.Excel,Response,True, fileName);
I also tried using ExportToStream from here which also hangs:
System.IO.Stream myStream;
byte[] byteArray;
myStream = boReportDocument.ExportToStream (ExportFormatType.PortableDocFormat);
I have tried different export formats, restarting IIS, etc. There seems to be a size limit or perhaps specific data scenarios that cause these methods to hang. Any workarounds or explanations for this behavior? Thanks!
Try this:
Public Shared Sub ExportDataSetToExcel(ByVal ds As DataTable, ByVal filename As String)
Dim response As HttpResponse = HttpContext.Current.Response
response.Clear()
response.Buffer = True
response.Charset = ""
'response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
response.ContentType = "application/vnd.ms-excel"
'response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & ".xls")
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
Dim dg As New DataGrid()
dg.DataSource = ds
dg.DataBind()
dg.RenderControl(htw)
response.Charset = "UTF-8"
response.ContentEncoding = System.Text.Encoding.UTF8
response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble())
response.Output.Write(sw.ToString())
response.[End]()
End Using
End Using
End Sub
and in your viewer add :
DT = New DataTable
DT = (Your Method)
ExportDataSetToExcel(DT, "ExportedReport")
also add :
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
ReportObject.Close()
ReportObject.Dispose()
End Sub
So report would not add restrictions on the number of loaded reports.
i am getting error A generic error occurred in GDI+
on line
bit.Save(str, Imaging.ImageFormat.Png)
please help me on this here is my full code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsNothing(Request.QueryString("id")) = False Then
If Val(Request.QueryString("id")) > 0 Then
Dim dsFiles As New DataSet
dsFiles = oFileData.GetFile(Val(Request.QueryString("id")))
Dim bindata() As Byte = dsFiles.Tables(0).Rows(0).Item("FileData")
Dim str As New MemoryStream
str.Write(bindata, 0, dsFiles.Tables(0).Rows(0).Item("FileSize"))
Dim bit As Bitmap = New Bitmap(str)
Response.ContentType = ".png"
bit.Save(str, Imaging.ImageFormat.Png)
str.WriteTo(Response.OutputStream)
str.Close()
Else
Response.Write("<script language=""javascript"" type=""text/javascript"">window.close();</script>")
End If
Else
Response.Write("<script language=""javascript"" type=""text/javascript"">window.close();</script>")
End If
End Sub
There may be many reasons - may be the content of byte array is not valid image data. In fact no need to create Bitmap or MemoryStream to write image data/bytes to response stream.
Try this,
Dim bindata() As Byte = dsFiles.Tables(0).Rows(0).Item("FileData")
Response.ContentType = "image/png"
Response.BinaryWrite(bindata)
Response.Flush()
Response.End()