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);
Related
I am trying to display .png / .jpg image in browser but the problem is instead of displaying the image in the browser it is getting downloaded. I have tried using content-disposition:inline as well but its downloading the complete aspx page. Can anyone help me with this. Below is my code
string filePath = "C:\\inetpub\\wwwroot\\Folder\\OSP\\20139000\\";
string filename = "test.jpg";
string contenttype = "image/" +
Path.GetExtension(filename.Replace(".", ""));
FileStream fs = new FileStream(filePath + filename,
FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
////Write the file to response Stream
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contenttype;
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
You miss
Response.Clear();
somewhere at the beginning of the script. Without clearing the response's buffer first, it already contains the text of the *.aspx page the script is run under.
Then, don't set the content's disposition to attachment, completely delete this line.
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.
I am saving a pdf file in the database by the following code
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string filetype = Path.GetExtension(FileUpload1.PostedFile.FileName);
int filesize = FileUpload1.PostedFile.ContentLength;
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] content = br.ReadBytes((Int32)fs.Length);
Objects.Insert_FilesToDatabase(filename, filetype, content,filesize);
and then, Iam trying to save the file from the database by clicking the link thru the following code.
void lnkDownload_Click(object sender, EventArgs e)
{
string filetype = Objects.GetFileType(Convert.ToInt32(txtslno.Text.Trim()));
string filename=Objects.GetFileName(Convert.ToInt32(txtslno.Text.Trim()));
int filesize = Objects.GetFileLength(Convert.ToInt32(txtslno.Text.Trim()));
byte[] bytfile = new byte[filesize+1000];
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",attachment;filename="+filename+".pdf");
Response.BufferOutput = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytfile);
Response.End();
}
Thru this code, I am able to download the pdf file but I am unable to open the pdf file. The error is the file is not decoded properly. Can you help me as to where am I going wrong?
I solved this problem thru the following code..
byte[] bytfile = Objects.GetFile(Convert.ToInt32(txtslno.Text.Trim()));
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename="+filename);
Response.AddHeader("Content-Length", bytfile.Length.ToString());
Response.OutputStream.Write(bytfile, 0, bytfile.Length);
Response.Flush();
Response.End();
I am just not writing the binary content to the output pdf stream in my previous code..
Thank you for your support
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();
To store the word doc in SQL I have this:
byte[] bytes = new byte[uploader.UploadedFiles[0].InputStream.Length];
var storedFile = new email_attachment();
string strFullPath = uploader.UploadedFiles[0].FileName;
string strFileName = Path.GetFileName(strFullPath);
storedFile.email_attachment_id = Guid.NewGuid();
storedFile.emailer_id = new Guid(dropMailers.SelectedValue);
storedFile.file_name = strFileName;
storedFile.file_data = bytes;
db.email_attachments.InsertOnSubmit(storedFile);
db.SubmitChanges();
To get it back I use this:
var storedFile = db.email_attachments.Where(a => a.email_attachment_id.ToString() == dropAttachments.SelectedValue).Single();
string strPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Storage/Email/Attachments");
File.WriteAllBytes(Path.Combine(strPath, storedFile.file_name), storedFile.file_data.ToArray());
System.IO.FileInfo file = new System.IO.FileInfo(Path.Combine(strPath, storedFile.file_name));
if (file != null && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
//Response.Write("This file does not exist.");
}
Problems: The doc I get back is blank, and I also believe saving it in the file system and then writing it to the response stream isn't very efficient. I'm thinking that step could be skipped. Any help or info would be much appreciated.
Let's look at this code to start with:
byte[] bytes = new byte[uploader.UploadedFiles[0].InputStream.Length];
var storedFile = new email_attachment();
string strFullPath = uploader.UploadedFiles[0].FileName;
string strFileName = Path.GetFileName(strFullPath);
storedFile.email_attachment_id = Guid.NewGuid();
storedFile.emailer_id = new Guid(dropMailers.SelectedValue);
storedFile.file_name = strFileName;
storedFile.file_data = bytes;
db.email_attachments.InsertOnSubmit(storedFile);
db.SubmitChanges();
I can see you creating an empty array - but I can't see where you're populating it anywhere. Shouldn't you be reading from the InputStream instead of just finding out its length?
(You may well want to copy from the input stream into a MemoryStream, and then use ToArray to get a byte array out at the end. There's plenty of sample code around for copying a stream - and in .NET 4 there's even the WriteTo method which makes it easier.)
I haven't even looked at the later code yet - first let's make sure you actually get some data into the database first...
To write to the db:
byte[] bytes = new byte[uploader.UploadedFiles[0].InputStream.Length];
uploader.UploadedFiles[0].InputStream.Read(bytes, 0, bytes.Length);
var storedFile = new document();
string strFullPath = uploader.UploadedFiles[0].FileName;
string strFileName = Path.GetFileName(strFullPath);
storedFile.document_id = Guid.NewGuid();
storedFile.content_type = uploader.UploadedFiles[0].ContentType;
storedFile.original_name = strFileName;
storedFile.file_data = bytes;
storedFile.date_created = DateTime.Now;
db.documents.InsertOnSubmit(storedFile);
db.SubmitChanges();
And to get the document back out:
var storedFile = db.documents.Where(a => a.document_id.ToString() == dropAttachments.SelectedValue).Single();
Response.Clear();
Response.ContentType = "application/x-unknown";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + storedFile.original_name + "\"");
Response.BinaryWrite(storedFile.file_data.ToArray());
Response.End();
Found my answer here: http://imar.spaanjaars.com/414/storing-uploaded-files-in-a-database-or-in-the-file-system-with-aspnet-20#Downloads