I am trying to download an Excel file from the server on a button click, but it is not happening. It simply executes the code but the download is not happening.
Protected Sub btn_dwnldexcel_Click(sender As Object, e As EventArgs) Handles btn_dwnldexcel.Click
Dim fileToDownload = Server.MapPath("./Data/nd_format.xls")
''Response.ContentType = "application/octet-stream"
Response.ContentType = "application/vnd.ms-excel"
Dim cd = New ContentDisposition()
cd.Inline = False
cd.FileName = Path.GetFileName(fileToDownload)
Response.AppendHeader("Content-Disposition", cd.ToString())
Dim fileData As Byte() = System.IO.File.ReadAllBytes(fileToDownload)
Response.OutputStream.Write(fileData, 0, fileData.Length)
End Sub
Any idea would be appreciated.
Instead of trying to send the data from the same page, it is better to use a generic handler which does not have the overheads of processing an aspx page.
So, if you add a new item to the project and find "Generic handler (.ashx)" (or similar), and use code like this:
Imports System.Web
Imports System.Web.Services
Imports System.IO
Public Class DownloadExcelFile
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim actualFile = Server.MapPath("~/Data/nd_format.xls")
If File.Exists(actualFile) Then
context.Response.ContentType = "application/octet-stream"
context.Response.AddHeader("content-disposition", "attachment; filename=""" & Path.GetFileName(actualFile) & """")
context.Response.TransmitFile(actualFile)
Else
context.Response.Clear()
context.Response.TrySkipIisCustomErrors = True
context.Response.StatusCode = 404
context.Response.Write("<html><head><title>File not found</title><style>body {font-family: Arial,sans-serif;}</style></head><body><h1>File not found</h1><p>Error.</p></body></html>")
context.Response.End()
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Then you can use a hyperlink instead of a Button:
Download Excel File
(You can style the hyperlink as a button with CSS if required.)
Related
I am trying to create a simple encryption program with visual basic on visual studio. My program is to encrypt an image then decrypt it. The system is saying that the request is not supported. As a note I am just learning about encrypting and not sure if I am even doing this correctly. Any comments or help would be much appreciated.
Error is from this: File.Encrypt(FileName)
if my encrypt is creating an error then my decrypt will most likely as well
Imports System
Imports System.IO
Imports System.Security.Cryptography
Partial Class _Default
Inherits System.Web.UI.Page
'My Encrypt button that takes the file from my FileUpload tool and Encrypts it, then outputs on my label
'that the file was successfully encrypted
Protected Sub EncryptButton_Click(sender As Object, e As EventArgs) Handles EncryptButton.Click
Dim FileName As String = FileUpload1.FileName
File.Encrypt(FileName)
Label1.Text = "Encrypt" + FileName
End Sub
'My Decrypt button that takes the file from my FileUpload tool and Encrypts it, then outputs on my label
'that the file was successfully encrypted
Protected Sub DecryptButton_Click(sender As Object, e As EventArgs) Handles DecryptButton.Click
Dim FileName As String = FileUpload1.FileName
File.Decrypt(FileName)
Label1.Text = "Decrypt" + FileName
End Sub
'Load page that will display a success output on the label if the upload is completed
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If FileUpload1.HasFile = True Then
Label1.Text = "Success"
Else
Label1.Text = "Failed"
End If
End Sub
Protected Sub CustomValidator1_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'Verify the control has a file
If Not FileUpload1.HasFile Then
CustomValidator1.ErrorMessage = "A file is required in order to proceed"
args.IsValid = False
Else
'next 2 lines are all one line
Dim ext As String =
System.Web.VirtualPathUtility.GetExtension(FileUpload1.FileName).ToUpper()
If Not ext = ".GIF" And Not ext = ".JPG" And Not ext = ".PNG" Then
'next 2 lines are all one line
CustomValidator1.ErrorMessage = String.Concat("Invalid file type '", ext, "' -must be .gif or .jpg or .png to continue")
args.IsValid = False
Else
args.IsValid = True
End If
End If
End Sub
End Class
I searched for "System.IO.IOException" and found Troubleshooting Exceptions: System.IO.IOException which states
Make sure the file and directory exist.
Then looking at the code:
Dim FileName As String = FileUpload1.FileName
I see that there is no directory specified for the file. So, you need to use Path.Combine so that you can give File.Encrypt the full filename including the path.
(There is no indiction in the posted code of which directory the uploaded file is in, so I can't help further with that. It could be that FileUpload1 has a property which gives that.)
I have big file (about 2GB) to distribute to our customer, My website is written by asp.net vb, this is my file download handler:
Public Class FileHandler
Implements IHttpHandler
Public Sub ProcessRequest(ByVal httpcontext As HttpContext) Implements IHttpHandler.ProcessRequest
If HttpContext.User.Identity.IsAuthenticated Then
Dim FileName As String = HttpContext.Request.QueryString("File")
HttpContext.Response.Buffer = False
HttpContext.Response.Clear()
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" & FileName)
HttpContext.Response.ContentType = "application/exe"
HttpContext.Response.TransmitFile("~/download/ExE/" & FileName)
HttpContext.Response.Flush()
HttpContext.Response.Close()
End If
End Sub
Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
My problem is this handler sometimes could not work properly.
Most customer could download it by this handler, but some customer click the download link, it will endless waiting for server's response, after long time waiting, it shows the error page says the IE cannot display the webpage. some customer try to download the file from IE8, it will show the error page directly.
I am really appreciate any one can help with this issue. Thank you!
I use a button or just a plain link to the file itself, I've never had to use a handler to download files.
For example, on the aspx I have a button and in the code behind I send the user to the file using the response object:
Protected Sub Button_DownloadFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_DownloadFile.Click
Response.AddHeader("Content-Disposition", "attachment; filename=TheFileName.ext")
Response.WriteFile("~/App_Data/TheFileName.ext")
END SUB
Im trying to send a Docx file via this form that I made, the email sends fine.
but the docx file gets back corrupted..
this is my backgroudn code:
'Add the namespace for the email-related classes
Imports System.Net.Mail
Partial Class SendAttachment
Inherits System.Web.UI.Page
Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click
'Make sure a file has been uploaded
If String.IsNullOrEmpty(AttachmentFile.FileName) OrElse AttachmentFile.PostedFile Is Nothing Then
Throw New ApplicationException("Egad, a file wasn't uploaded... you should probably use more graceful error handling than this, though...")
End If
' UPDATE THIS VALUE TO YOUR EMAIL ADDRESS
Const ToAddress As String = "pelleg#shakuff.co.il"
'(1) Create the MailMessage instance
Dim mm As New MailMessage(UsersEmail.Text, ToAddress)
'(2) Assign the MailMessage's properties
mm.Subject = "שלוחת קורות חיים"
mm.Body = Body.Text
mm.IsBodyHtml = False
'Attach the file
mm.Attachments.Add(New Attachment(AttachmentFile.PostedFile.InputStream, AttachmentFile.FileName))
'(3) Create the SmtpClient object
Dim smtp As New SmtpClient
'(4) Send the MailMessage (will use the Web.config settings)
smtp.Send(mm)
'Show the EmailSentForm Panel and hide the EmailForm Panel
EmailSentForm.Visible = True
EmailForm.Visible = False
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'On the first page load, hide the EmailSentForm Panel
EmailSentForm.Visible = False
End If
End Sub
End Class
its the sendemail.aspx.vb file.
any suggestions?
totally off the top of my head, but try setting:
AttachmentFile.PostedFile.InputStream.Position = 0
before you call:
'Attach the file mm.Attachments.Add(New Attachment(AttachmentFile.PostedFile.InputStream, AttachmentFile.FileName))
I'm trying to pass a value to a feedbacklabel after an asynch upload.
Protected Sub FileUploadComplete(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim filename As String = System.IO.Path.GetFileName(AsyncFileUpload1.FileName)
AsyncFileUpload1.SaveAs(Server.MapPath("tmp/") + filename)
lblFeedback.Text = "File uploaded. Processing information"
'Get a StreamReader class that can be used to read the file
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(Server.MapPath("tmp/") + filename)
While objStreamReader.Peek <> -1
lblFeedback.Text += objStreamReader.ReadLine()
End While
objStreamReader.Close()
Catch ex As Exception
End Try
End Sub
The thing is I need to display how many rows have been uploaded in the database. How can I do this?
Add at the end of FileUploadComplete procedure following method call (I hope you can translate it from C# to VB):
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "feedback", string.Format("top.$get('{0}').innerText = '{1}'", lblFeedback.ClientID, lblFeedback.Text), true);
I need help with the following issue. I parse XML and do a XSLT transformation. Everything is fine with Stylus Studio. But with ASP.NET I can't parse and output.
min.aspx.vb
Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Xsl
Imports System.IO
Partial Class Poseidon_min
Inherits System.Web.UI.Page
Protected Sub Literal1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Literal1.PreRender
Dim strXSLTFile As String = "http://www.kiris-alinda.de/Poseidon/Hotelangebote.xslt"
Dim strXMLFile As String = "http://www.kiris-alinda.de/Poseidon/PosXMLReq/PosXMLReqSearch.php?htc=AYTLIND"
Dim reader As XmlReader = XmlReader.Create(strXMLFile)
Dim objXSLTransform As New XslCompiledTransform()
objXSLTransform.Load(strXSLTFile)
Dim htmlOutput As New StringBuilder()
'Dim htmlWriter As TextWriter = New StringWriter(htmlOutput)
'objXSLTransform.Transform(reader, Nothing, htmlWriter)
Me.Literal1.Text = htmlOutput.ToString()
reader.Close()
End Sub
End Class
Why is it not possible to output <xsl:value-of select="PosXmlResponse/search/date/#min"/> from the XSLT in ASP.NET?
Take a look at this :
XML / XSLT Transformation
You have to use an XML Server Control on the ASPX page and then setting up XSLT Transformation
I use this code:
Public Shared Function Transform(xml As String, xsl As String, argsList As XsltArgumentList) As String
Dim selectedXml As XDocument = XDocument.Parse(xml)
Dim xmlTransform As New XslCompiledTransform()
Dim htmlOutput As New StringBuilder()
Dim writer As XmlWriter = XmlWriter.Create(htmlOutput)
xmlTransform.Load(New XmlTextReader(New StringReader(xsl)))
xmlTransform.Transform(selectedXml.CreateReader(), argsList, writer)
Return htmlOutput.ToString()
End Function