Download PDF Document on Save as dialog - asp.net

I am using following code for downloading PDF document in save as mode but there is a problem in IE,
anyone can resolve this prohlem?
private void DownloadFile(string fname, bool forceDownload)
{
string path = MapPath(fname);
string name = Path.GetFileName(fname);
string ext = Path.GetExtension(fname);
string type = "";
Response.ClearHeaders();
Response.ClearContent();
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".pdf":
type = "application/pdf";
break;
case ".doc":
case ".docx":
case ".rtf":
type = "Application/msword";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition", "attachment; filename=" + name);
}
if (type != "")
{
Response.ContentType = type;
Response.WriteFile(path);
Response.End();
}
}
thanks
Asim Hashmi

Maybe because you're using SSL?
check this: http://support.microsoft.com/kb/316431

Related

Open button do not works properly in downloading with a linkbutton

There is a section in my site that users can download files. I want that As users push the download button and hit "Open" button instead of "save" button, the download get open with it's own program. For example a pdf file should not en with ms word. Now my problem is that, as a user open the file an XML extension will be added to the download URL!!
For example it should be:
www.mysite.com/inputfile/12.dox
but instead of that, it goes for
www.mysite.com/inputfile/12.dox.xml
Here is my cod:
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
int idx = Convert.ToInt32(e.CommandArgument);
string Manuscript = GridView2.DataKeys[idx].Value.ToString();
string fileName = System.IO.Path.GetFileName(Manuscript);
string contenttype = String.Empty;
string ext = Path.GetExtension(fileName);
Response.ClearContent();
Response.ClearHeaders();
switch (ext)
{
case ".doc":
contenttype = "application/msword";
break;
case ".docx":
contenttype = "application/msword";
break;
case ".xls":
contenttype = "application/msexcel";
break;
case ".xlsx":
contenttype = "application/msexcel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
Response.ContentType = contenttype;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(Server.MapPath(Manuscript));
Response.End();
}

How to open a file with it's own program with a linkbutton

I have developed a website using Asp.net. In a section of my program users need to download some variable files. (Jpeg,Pdf,doc,docx...) As they push the download button and hit "Open" button instead of "save" button, the file will open with Adobe Acrobat. The problem is that if it is a word file, again it will be open with Adobe Acrobat!
How can i avoid this and each file open with it's own program?
I used this cod in my behind cod:
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
int idx = Convert.ToInt32(e.CommandArgument);
string Manuscript = GridView2.DataKeys[idx].Value.ToString();
string fileName = System.IO.Path.GetFileName(Manuscript);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(Server.MapPath(Manuscript));
Response.End();
}
Like this :
string ext = System.IO.Path.GetExtension(this.File1.PostedFile.FileName);
string contenttype = String.Empty;
OR
string ext = Path.GetExtension(filename);
switch(ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
Use
FileInfo fInfo = new FileInfo(fileName);
string fileExtn = fInfo.Extension;

How do display the word document in asp.net page retrieved from SQL Server database

How do display a Word document on an asp.net page retrieved from a SQL Server database table?
I have uploaded the word document into database, please see the code,
Now I want to display the word document details in gridview, when I click the word document name in the gridview then the word document should display in webpage. Please help me how to do this.
protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
" values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
SqlConnection con = new SqlConnection("user id=sa;password=123;database=Shashank;data source=Shashank");
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
To my knowledge you have to convert the word document to .html to display it in a web page itself. You can check out this article that shows you how to do it. http://www.c-sharpcorner.com/UploadFile/munnamax/WordToHtml03252007065157AM/WordToHtml.aspx
I guess what I would do is convert the ms doc file to HTML at upload and then store that along with the .doc or .docx. The HTML you would select and display it in an iframe and the actual .doc file you could use if the user wanted to download it.

Response.Flush() method is not working

Response.Flush method is not working. I am getting the data at pdfContent but it is not opening the PDF documnet. Below is the code. Please help.
public ActionResult PdfClick(int requestid)
{
BusinessRequestController bsnrqstcntrlr = new BusinessRequestController();
try
{
int DocId = (new BusinessRequestBR()).GetBaseLineDocumentsForSearch(requestid);
byte[] PdfContent = (new BusinessRequestHelper()).GetBaseLineDonload(DocId);
Response.Buffer = true;
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + "BaseLine_Doc" + "_" + DocId + ".pdf");
Response.BinaryWrite(PdfContent);
Response.Flush();
return Content("");
}
catch (Exception ex)
{
throw this.log.CreatePropagatedException(ex);
}
Instead of using
return Content("")
use this:
return File(
PdfContent,
"application/pdf",
string.Format("BaseLine_Doc{0}.pdf", DocId)
)
There is no need to manipulate the response. Just return the correct result type.
Pulling out code from my running project
Response.Clear();
Response.AddHeader("Content-Disposition","attachment; filename=\"" + file[0].Name + "\"");
Response.AddHeader("Content-Length", fileSize.ToString(_culture));
Response.ContentType = Path.GetExtension(file[0].Name).GetMimeType();
Response.BufferOutput = false;
Response.AddHeader("Accept-Ranges", "bytes"); //tell the client that we accept byte-range requests
while (totalBytesRead < fileSize)
{
if (!Response.IsClientConnected)
{
System.Diagnostics.Debug.WriteLine("--> Client disconnected");
break;
}
int bytesRead = fs.Read(buffer, 0, buffer.Length);
Response.OutputStream.Write(buffer, 0, bytesRead);
Response.Flush();
totalBytesRead += bytesRead;
}
Response.End();
This code works for me every time, please manipulate according to your need.
Note: Variables are defined above the code.

uploading more than of 1mb is not possible

i have used below structure for my table in database. i can not upload files more than of 1mb in the database, please help what is the problem.
fileid(int), FileName(varchar(100)), ContentType (varchar(75)), data varbinary(MAX)
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
Transmittallistfortest transmittalList = (Transmittallistfortest)DetailsView1.FindControl("Transmittallistfortest1");
GridView g3 = transmittalList.FindControl("GridViewTtransmittals") as GridView;
foreach (GridViewRow di in g3.Rows)
{
if (di.RowType == DataControlRowType.DataRow)
{
RadioButton rad = di.FindControl("RadioButton1") as RadioButton;
//Giving Error:Object reference not set to an instance of an object.
rad.CheckedChanged += new EventHandler(MyCheckedChangeEventHandler);
if (rad != null && rad.Checked)
{
var w = di.RowIndex;
string s = ((HyperLink)di.Cells[1].Controls[0]).Text;
var tr = from transmittal in _DataContext.tbltransmittalNos
where transmittal.TRANSMITTAL == s
select transmittal.TransID;
int _transid = tr.SingleOrDefault();
// int _transid = Convert.ToInt32(tr.SingleOrDefault());
Label1.Text = _transid.ToString();
Label2.Text = s;
}
}
}
tblFile fn = new tblFile();
fn.DocId = _DocID;
fn.TransId = Convert.ToInt32(Label1.Text);
fn.FileName = filename;
fn.ContentType = contenttype;
fn.Data = bytes;
// BookAuthor bookAuthor = new BookAuthor();
_DataContext.tblFiles.InsertOnSubmit(fn);
_DataContext.SubmitChanges();
//doctranscon.TransmitToConid = Convert.ToInt32(ddlTransmittaltoCon.SelectedValue);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
// Update display
DisplayDocument();
}
}
You are not sharing your specific error but this is likely the cause. Increase the maxRequestLength size in your web.config file. The default is 4096 KB (4 MB).
<configuration>
<system.web>
<httpRuntime maxRequestLength="size in kbytes"
...
/>
Allocating an array size of data will, eventually, fail. Look into streaming semantics.
Check your configured maxRequestLength

Resources