Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Downloading file to client problem

Status
Not open for further replies.

aspdotnetuser

Programmer
Oct 10, 2008
45
GB
Hi,

I want to allow the user to download a .bmp file to their desktop, and I have the code working for this but when the file is downloaded it cannot be opened - why is this? Can anyone tell me what I am doing wrong? Here is the code
(exectuted when user clicks download button)

[blue]
String fileName;

fileName = ReceiptID.Remove(0, 6);

string url = " + fileName;

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

int bufferSize = 1;

[red]//Initialize the output stream[/red]
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=download.jpg");

Response.AppendHeader("ContentLength",resp.ContentLength.ToString());

Response.ContentType = "application/download";

[red]//Populate the output stream[/red]
byte[] ByteBuffer = new byte[bufferSize + 1];
MemoryStream ms = new MemoryStream(ByteBuffer, true);

Stream rs = req.GetResponse().GetResponseStream();

byte[] bytes = new byte[bufferSize + 1];

while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0)

{
Response.BinaryWrite(ms.ToArray());
Response.Flush();
}[/blue]
 
I managed to solve this, here is the code just in case anyone else comes accross this post trying to find out how to download files:

[blue]
String fname = "filename.bmp";

Boolean downloadFile = true;

string path = @"/Docs/" + fname;

string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".bmp":
type = "application/download";
break;

case ".htm":
case ".html":
type = "text/HTML";
break;

case ".txt":
type = "text/plain";
break;

case ".doc":
case ".rtf":
type = "Application/msword";
break;
}
}
if (downloadFile)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + name);
}
if (type != "")
Response.ContentType = type;
Response.WriteFile(path);
Response.End();
}[/blue]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top