When downloading a file from ASP .Net, the text file gets appended with HTML content
Asked Answered
S

3

6

I have made a page that allows users to upload files to the server using a FileUpload Control and handling its event with this code

Sub SaveAttachment()
    Dim root As String = "C:\temp\"
    Dim filename As String = FileUpload1.FileName
    Dim SaveName As String = root & filename
    FileUpload1.SaveAs(SaveName)
End Sub

That worked fine, I was able to see files getting uploaded, and the content of the files is intact (exactly a duplicate copy of the file that the user's upload).

Now for downloading the files back to the user (at a later time) I have written another page that reads the file name from a Request.Parameter ("file") and fetches that file to be downloaded to the user. I have written the Download.aspx page to handle downloading in the ASP part (no code behind was used):

<%@ Import Namespace="System.IO"%>
<script language="VB" runat="server">
Sub Page_Load(sender As Object, e As EventArgs)

        Dim root As String = "C:\temp\"
        Dim filepath As String = Request.Params("file")
        If Not filepath Is Nothing Then
            filepath = root & filepath
            If File.Exists(filepath) And filepath.StartsWith(root) Then
                Dim filename As String = Path.GetFileName(filepath)
                Response.Clear()
                Response.ContentType = "application/octet-stream"
                Response.AddHeader("Content-Disposition", _
                  "attachment; filename=""" & filename & """")
                Response.Flush()
                Response.WriteFile(filepath)
            End If
        End If

End Sub
</script>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>

I tried uploading images files and then downloading them again, and it worked fine. However, only when I upload text files that I get the content of that file appended with some HTML content.

Here is a sample file that I have uploaded Original File before uploading

Here is my sample text file

It consists of 3 lines only

And here is the file when I downloaded it back The same file when downloaded from the server

Here is my sample text file

It consists of 3 lines only
<form name="form1" method="post" action="FileDownload.aspx?file=sample_file.txt" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE5NTU5ODQyNTBkZNCYbOVZJDRUAOnIppQYkwHUSlb0" />
</div>

<span id="Label1">Label</span>
</form>

I went to the file on the server and opened it to make sure that the additional HTML content was there, but as I said, the file was uploaded perfectly. Only when it is downloaded does it contain appended HTML stuff.

What is it that I am doing wrong? What can I do to make this additional HTML code go away? Why does this problem only affect Text file, not images, EXE, XLS, DOC ,, etc?

Shrewd answered 21/7, 2012 at 7:54 Comment(4)
I am not sure if the images I uploaded showed up, I can't seem to know how to properly display uploaded screenshots, so I have dumped the contents of the files manually.Shrewd
I think there is a Response.End(); missing... And also use Path.Combine to build the complete path. If you don't use Response.End(); the rest of your page's mark up code will be transformed into the HTML code you see in your browser.Innocent
@Innocent that's right, as answered below.Shrewd
That's the thing with stackoverflow - while typing away, every now and then someone else is faster :-)Innocent
D
3

Make sure to end your Response by calling Response.End() after Response.WriteFile(filepath) or else your form will be appended to the stream and sent to the client.

It will affect other files as well though most likely only be seen as garbage at the end of the file and ignored by their respective applications.

Doorpost answered 21/7, 2012 at 7:57 Comment(0)
G
3

Response.redirect threw an exception. Shoaib's answer got me closer but it suppressed everything including the valid file content. What worked for me was reordering the statements as follows:

 Response.ContentType = ContentType
 Response.AppendHeader("Content-Disposition", "attachment; filename=" & originalFileName)
 Response.WriteFile(filePath)
 Response.Flush()
 Response.SuppressContent = True
 HttpContext.Current.ApplicationInstance.CompleteRequest()
Godgiven answered 14/6, 2016 at 17:16 Comment(0)
C
2

Is is not safe to use Response.End(), It will always return a System.Threading.ThreadAbortException:.. if debugged and seen in the catch block...

Alternative.. Use the following instead...

Response.Flush();
Response.SuppressContent = true;
Response.WriteFile(filepath);
HttpContext.Current.ApplicationInstance.CompleteRequest();
Compose answered 2/12, 2013 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.