Can't download image to client machine - c#

I have base64 string of an image. converting it to byte array & then converting it to memoryStream. How can i download this image to client machine. The base64 string or image is not saved on server/folder/anywhere. It is create dynamically. I have tried
1) Response.ContentType = "image/png" => gives exception obj not set to instant of an object. like this
Context.Response.Clear();
Context.Response.ClearHeaders();
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + registrationId + ".png");
Context.Response.ContentType = "image/jpeg";
Response.AddHeader("Content-Length", bytes.Length.ToString());
//Response.ContentType = "application/octet-stream";
Context.Response.BinaryWrite(bytes);
2) using web client => gives exception
using (WebClient client = new WebClient())
{
client.DownloadFile(ms1.ToString(), registrationId + ".png");
}
Any other solution?

Just try to change
Response.AddHeader("Content-Length", bytes.Length.ToString());
to
Context.Response.AddHeader("Content-Length", bytes.Length.ToString());
I think you doesn't have valid Page object in this context.

Related

Downloaded JPEG file not recognised on iPhone

When I download a JPEG file from and ASP Web Forms application using the following code, the image is not shown when the application runs from a browser (Safari) on an iPhone 5 - only a screen offering to open the file in Dropbox. Using Opera the download does not appear at all. It appears that IOS does not recognize the downloaded file as a displayable image. The download occurs as expected from a Windows desktop.
string sDownloadFile = Session["strImagePath"].ToString();
string sFileName = Session["sFileName"].ToString();
Response.ContentType = "application/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename='" + sFileName + "'");
Response.TransmitFile(sDownloadFile);
Response.End();
Using the code below (BinaryWrite rather than TransmitFile) I found that the iPhone would recognize downloaded file as a JPEG.
string sFileName = Session["sFileName"].ToString();// Original file name// System.IO.Path.GetFileName(sDownloadFile);
byte[] fileBytes = System.IO.File.ReadAllBytes(sDownloadFile);
SendFileBytesToResponse(fileBytes, sFileName);
private static void SendFileBytesToResponse(byte[] bytes, string sFileName)
{
if (bytes != null)
{
string downloadName = sFileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "application/jpeg");
response.AddHeader("Content-Disposition",
"attachment; filename=" + downloadName + "; size=" + bytes.Length.ToString());
response.Flush();
response.BinaryWrite(bytes);
response.Flush();
response.End();
}
}

Converting a byte[]-Array to ANSI

I am trying to convert a byte[] blob in an MSSQL database to Windows-1252 ANSI format using C# and Microsoft Lightswitch, and return the results to a file download.
This is what I thought should work...
I'm creating the string with
System.Text.Encoding v_Unicode = System.Text.Encoding.Unicode;
System.Text.Encoding v_ANSI_Windows_1252 = System.Text.Encoding.GetEncoding(1252);
string v_Content_1252 = v_ANSI_Windows_1252.GetString(System.Text.Encoding.Convert(v_Unicode, v_ANSI_Windows_1252, v_Unicode.GetBytes(v_Content)));
byte[] ansiArray = v_ANSI_Windows_1252.GetBytes(v_Content_1252);
and write it in the database. When I try to retrieve with
int v_fileId = Int32.Parse(context.Request.QueryString["p_FileId"]);
DataTableName v_fexpd = serverContext.DataWorkspace.ApplicationData.DataTableName_SingleOrDefault(v_fileId);
MemoryStream memStream = new MemoryStream(v_fexpd.Inhalt);
string v_Content= System.Text.Encoding.GetEncoding(1252).GetString(v_fexpd.Content);
context.Response.Clear();
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + v_fexpd.Filename);
context.Response.Write( v_Content );
context.Response.End();
... but it just returns Unicode. What am I doing wrong?
This is for anyone having a similar problem. The answer is to go the way over a Stream... What I did is the following:
// Create a temporary file, delete if it already exists
string MyFile = Path.GetTempPath() + v_fexpd.Dateiname;
if (File.Exists(MyFile)) {
File.Delete(MyFile);
}
using (TextWriter tw = new StreamWriter(MyFile.ToString(), true, System.Text.Encoding.GetEncoding(1252)))
tw.WriteLine(v_Inhalt);
context.Response.Clear();
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + v_fexpd.Dateiname);
context.Response.AddHeader("Content-Type", "text/csv; charset=windows-1252");
// Write the file - which at this point is correctly-encoded -
// directly into the output.
context.Response.WriteFile(MyFile);
context.Response.End();
// Leave no traces
File.Delete(MyFile);

TransmitFile is not working

I have a file, and it is full path (plus the file name) is in this variable:
fileTemporary
i want to download that file to the client.
i do this:
HttpContext.Current.Response.TransmitFile(fileTemporary);
but nothing happen, i mean when i click the button, this file executes, but nothing is being downloaded to the client. i don't see any file on the browser of the client.
what mistake did i do please?
If you use MVC you can:
[HttpGet]
public virtual ActionResult GetFile(string fileTemporary)
{
// ...preparing file path... init fileTemporary.
var bytes = System.IO.File.ReadAllBytes(fileTemporary);
var fileContent = new FileContentResult(bytes, "binary/octet-stream");
Response.AddHeader("Content-Disposition", "attachment; filename=\"YourFileName.txt\"");
return fileContent;
}
If you use ASP.NET or whatever you can use following (sorry, my old code, but you can understand approach):
var bytes = System.IO.File.ReadAllBytes(fileTemporary);
SendFileBytesToResponse(bytes, fileName);
public static bool SendFileBytesToResponse(byte[] bytes, string sFileName)
{
if (bytes!= null)
{
string downloadName = sFileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition",
"attachment; filename=" + downloadName + "; size=" + bytes.Length.ToString());
response.Flush();
response.BinaryWrite(bytes);
response.Flush();
response.End();
}
return true;
}
Without reingeneering your solution:
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "binary/octet-stream");
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName);
System.Web.HttpContext.Current.Response.TransmitFile(fileName);
If you would like browser to interpret you file right, you will need to specify header "Content-Type" more precise.
Please see list of content types

Word and Excel files not getting downloaded in my asp.net website

the below code works if I try to download a .txt/.msg/.pdf/.png/.jpg but it fails if I try to download exccel or word files. Can anybody please help
Response.ContentType = "APPLICATION/OCTET-STREAM";
//Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
fileUrl = Server.UrlDecode(fileUrl);
System.String disHeader = "attachment; filename=\"" + fileUrl + "\"";
Response.AppendHeader("Content-Disposition", disHeader);
// transfer the file byte-by-byte to the response object 
System.IO.FileInfo fileToDownload = new System.IO.FileInfo(fileUrl);
Response.Flush();
Response.WriteFile(fileToDownload.FullName);

File downloading strange issue

I saved the document file/pdf file or txt file in the database. Now to get that File I am using the code below.
JobApplicantResume oApplicantResumne = new JobApplicantResume();
DataSet dsApplicantResume = oApplicantResumne.GetJobApplicantResumeByJobApplicantResumeId(1552);//1552 Long value
Response.ClearContent();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/xx-xxxx";
Response.AddHeader("Content-Disposition", "attachment;filename=" + dsApplicantResume.Tables[0].Rows[0]["sFileName"].ToString());
//Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Byte[] bytes = (Byte[])dsApplicantResume.Tables[0].Rows[0]["binFile"];
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
It is giving the exact file. No problem is there to open the file.
In some other page I used the same code:
JobApplicantResume oApplicantResumne = new JobApplicantResume();
DataSet dsApplicantResume = oApplicantResumne.GetJobApplicantResumeByJobApplicantResumeId(1552);//1552 Long value
Response.ClearContent();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/xx-xxxx";
Response.AddHeader("Content-Disposition", "attachment;filename=" + dsApplicantResume.Tables[0].Rows[0]["sFileName"].ToString());
//Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Byte[] bytes = (Byte[])dsApplicantResume.Tables[0].Rows[0]["binFile"];
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
It is also giving a file to download. But when I open it the data are coming in some different format.
Like:
؟½ï؟½ï؟½ï؟½ï؟½ï؟
Junk data. I could not understand why the problem is coming. If any one faced this similar kind of issue or any suggestion / help will be very much helpful to overcome this problem.
Thanks a lot for your attention.
Try to add Unicode Byte-Order-Mark full example.
//add the BOM
byte[] bBOM = new byte[] { 0xEF, 0xBB, 0xBF };
byte[] bContent = ms.ToArray();
byte[] bToWrite = new byte[bBOM.Length + bContent.Length];
//combile the BOM and the content
bBOM.CopyTo( bToWrite, 0 );
bContent.CopyTo( bToWrite, bBOM.Length );
//write to the client
HttpContext.Current.Response.Write( Encoding.UTF8.GetString( bToWrite ) );
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();

Categories