So, I have a web application that saves some attachments into SQL database as VarBinary(max), everything working smoothly until I realized that when I download the attachment from the database, the file is very big comparing to the original size, so a file with 400KB, the downloaded one would be 5MB! what I'm doing wrong?
The upload code is:
Dim img As FileUpload = CType(FileUpload1, FileUpload)
Dim imgByte As Byte() = Nothing
If img.HasFile AndAlso Not img.PostedFile Is Nothing Then
Dim File As HttpPostedFile = FileUpload1.PostedFile
imgByte = New Byte(File.ContentLength - 1) {}
File.InputStream.Read(imgByte, 0, File.ContentLength)
cmd.Parameters.AddWithValue("#filetype", Path.GetExtension(FileUpload1.FileName).ToLower)
cmd.Parameters.AddWithValue("#attachment", imgByte)
End If
The download code:
Dim imagem As Byte() = CType((dr("attachment")), Byte())
Response.Clear()
Response.AddHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0")
Response.AddHeader("Pragma", "no-cache")
Response.AddHeader("Content-Description", "File Download")
Response.AddHeader("Content-Type", "application/force-download")
Response.AddHeader("Content-Transfer-Encoding", "binary\n")
Dim fileName As String = "attachment; filename=" & "DOC_REFNO_" & "_" & regref_txt.Text.Replace("/", "_") & dr("filetype")
Response.AddHeader("content-disposition", fileName)
Response.BinaryWrite(imagem)
Thank you all.
so I found out that the download code is not correct, I changed it to the following code and worked perfectly.
Dim imagem As Byte() = CType((dr("attachment")), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = ContentType
Dim fileName As String = "attachment; filename=" & "DOC_REFNO_" & "_" & regref_txt.Text.Replace("/", "_") & dr("filetype")
Response.AddHeader("content-disposition", fileName)
Response.BinaryWrite(imagem)
Response.Flush()
Response.End()
Related
I have been breaking my head for the last two days and can't get this to work. I have a report, which I am exporting to Excel and saving on the server file directory. That part works perfectly, I can see the file, and open it, all good. The issue relies on when I try to send it to the browser for download from the server. It does not download anything, I do see the Response Header with all the info on the browser but nothing happens.
Here's one of my many tries
Private Sub dxgvPOAll_ToolbarItemClick(source As Object, e As ASPxGridViewToolbarItemClickEventArgs) Handles dxgvPOAll.ToolbarItemClick
Select Case e.Item.Name
Case "ExportAll"
Using report As DevExpress.XtraReports.UI.XtraReport = New POs_Dashboard_Report()
Using ms As New System.IO.MemoryStream()
report.Name = "Backorder Tickets"
report.ExportOptions.PrintPreview.SaveMode = DevExpress.XtraPrinting.SaveMode.UsingSaveFileDialog
Dim xlsxExportOptions As New DevExpress.XtraPrinting.XlsxExportOptions() With {.ExportMode = DevExpress.XtraPrinting.XlsxExportMode.SingleFile, .ShowGridLines = True, .FitToPrintedPageHeight = True}
Dim folderPath As String = "~/Account/TemporaryFiles/" & Utilities.RetrieveEmployeeNumber() & "/" & Guid.NewGuid.ToString & "/"
Dim serverPath As String = Server.MapPath(folderPath)
Dim xlsxExportFilePath As String = serverPath & report.Name & ".xlsx"
Dim folderInf As New DirectoryInfo(serverPath)
If Not folderInf.Exists Then folderInf.Create()
report.ExportToXlsx(xlsxExportFilePath, xlsxExportOptions)
Try
Dim objRequest As FileWebRequest = CType(WebRequest.Create(xlsxExportFilePath), FileWebRequest)
Dim objResponse As FileWebResponse = CType(objRequest.GetResponse(), FileWebResponse)
Dim bufferSize As Integer = 1
Response.Clear()
Response.ClearHeaders()
Response.ClearContent()
Response.AppendHeader("Content-Disposition:", "attachment; filename=" & xlsxExportFilePath)
Response.AppendHeader("Content-Length", objResponse.ContentLength.ToString())
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Dim byteBuffer As Byte() = New Byte(bufferSize + 1 - 1) {}
Dim memStrm As MemoryStream = New MemoryStream(byteBuffer, True)
Dim strm As Stream = objRequest.GetResponse().GetResponseStream()
Dim bytes As Byte() = New Byte(bufferSize + 1 - 1) {}
While strm.Read(byteBuffer, 0, byteBuffer.Length) > 0
Response.BinaryWrite(memStrm.ToArray())
Response.Flush()
End While
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Catch e1 As ThreadAbortException
Catch ex As Exception
End Try
End Using
End Using
End Select
End Sub
Here's what I see on the browser's Response-Header:
I am downloading a file from folder but this code of me doesn't download. It doesn't throw any error but doesn't download either.
Dim req As WebClient = New WebClient()
Dim response As HttpResponse = HttpContext.Current.Response
Dim filePath As String = "~/Downloads/MyExcelFile.xls"
response.Clear()
response.ClearContent()
response.ClearHeaders()
response.Buffer = True
response.AddHeader("Content-Disposition", "attachment;filename=Filename.extension")
'Dim data As Byte() = req.DownloadData(Server.MapPath(filePath))
'response.BinaryWrite(data)
response.TransmitFile(Server.MapPath(filePath))
'response.End()
try
response.WriteFile("some file");
response.Flush();
response.Close();
also consider Andrew's response on handler type - ashx is usually cleaner, with webform you might have other things that happen during page life cycle.
I am facing a strange error, i have a code in vb.net which basically just downloads an excel based on the dataset i have created. Everything seems to work fine and the file is downloaded but when i try to open the file, the file is corrupted.
I assume there is a problem in the code or maybe i am missing something, here is the code i am using:
dgGrid.DataSource = DS2.DefaultView ' This is where i do the Databinding
dgGrid.HeaderStyle.Font.Bold = True
dgGrid.DataBind()
ExcelFile = name & ".xls"
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", ExcelFile))
'Response.ContentType = "application/ms-excel"
Response.Charset = "utf-8"
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
'Response.ContentType = "application/octet-stream"
dgGrid.RenderControl(htwWriter)
Response.ContentEncoding = System.Text.Encoding.Unicode
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble())
Dim style As String = "<style>.textmode{mso-number-format:\#;}</style>"
Response.Write(style)
Response.Output.Write(stwWriter.ToString())
Response.End()
'Response.ContentType = "application/octet-stream"
Response.Close()
Response.Flush()
'Response.Write()
'Response.End()
Thanks, any help would be appreciated :(
Add the following line after flushing the file.
HttpContext.Current.Response.Close();
HttpContext.Current.Response.End();
I am using following code for file deletion on server after downloading at client site.
The code is working from visual studio but NOT working when website is hosted even on the coding machine.
'To save the word file at temp location with unique name
Dim varDate As String = DateTime.Now.ToString("yyyyMMdd_hhmmss_fff")
Dim theFileName As String = Server.MapPath("~/Temp/Report_" & varDate & ".docx")
oWord.ActiveDocument.SaveAs(theFileName)
oWord.ActiveDocument.Close()
oWord.Quit()
Dim filefullname As System.IO.FileInfo = New System.IO.FileInfo(theFileName)
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=Observation_Report.docx")
Response.AddHeader("Content-Length", filefullname.Length.ToString())
Response.ContentType = "application/octet-stream"
Response.WriteFile(filefullname.FullName)
Response.Flush()
System.IO.File.Delete(theFileName)
Response.End()
I have a code that writes a pdf file into an aspx page, but the problem is that when I want to save this file it saves with aspx extension... for example:
It saves as myPDFfile.aspx and I want to save it as myPDFfile.pdf
and I have to change the extension to .pdf to be able to open it.
How can I change the extension programatically?
My code:
Dim pdfPath As String = path + Session("factura").ToString.Trim + ".pdf"
Dim client As New WebClient()
Dim buffer As [Byte]() = client.DownloadData(pdfPath)
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.BinaryWrite(buffer)
You should add the Content-Disposition header :
Dim pdfPath As String = path + Session("factura").ToString.Trim + ".pdf"
Dim client As New WebClient()
Dim buffer As [Byte]() = client.DownloadData(pdfPath)
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.AddHeader("content-disposition", "attachment; filename=myPDFfile.pdf")
Response.BinaryWrite(buffer)
You should also read this question and its answer as it will leads you to potential issue with filename characters.
You need to add a content-disposition header with the file name.
Response.AddHeader("content-disposition", "attachment; filename=myPDFfile.pdf");
This is part of RFC 2616, section 19.