本文介绍了使用C#从ASP.NET中的数据库中重写pfd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace BootStrap.fa
{
/// <summary>
/// Summary description for ProductCatalogHandler
///
public class ProductCatalogHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int productId;
if (int.TryParse(context.Request.QueryString["ci"], out productId))
{
try
{
using (var db = new Data.ModelContainer1())
{
var catalog = db.Catalogs.Where(c => c.Product != null && c.Product.Id == productId).FirstOrDefault();
if (catalog == null || catalog.CatalogFile == null)
{
var returnUrl = context.Request.QueryString["ReturnURL2"];
context.Response.Redirect(returnUrl);
return;
}
else
{
var content = (catalog.CatalogFileExt != null) ? catalog.CatalogFileExt : "application/pdf";
var filename = (catalog.CatalogFileName != null) ? catalog.CatalogFileName : "Catalog.pdf";
filename = filename.Replace(" ", "");
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.Clear();
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.AddHeader("Content-Length", catalog.CatalogFile.Length.ToString());
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
MemoryStream memory = new MemoryStream(catalog.CatalogFile);
context.Response.OutputStream.Write(memory.ToArray(), 0, memory.ToArray().Length);
HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Close(); HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}
catch { }
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
我尝试了什么:
当我直接在Chrome或Firefox下载(打开)pdf时,浏览器显示无效代码,地址栏显示带有htm扩展名的下载文件。
请帮帮我。
谢谢
What I have tried:
When I download (open) pdf directly in Chrome or Firefox , browser show invalid code and in address bar show downloaded file with "htm" extensions.
Please Help me.
Thanks
推荐答案
// create a byte array to store your memory stream
byte[] fileArray = new byte[memory.Length];
memory.Read(fileArray, 0, Convert.ToInt32(memory.Length));
// clear content & headers
context.Response.ClearContent();
context.Response.ClearHeaders();
// the actual string you require is ".pdf","application/pdf"
// The additional '\' are used to escape the quotes within the string
context.Response.ContentType = "\".pdf\",\"application/pdf\""
context.Response.AddHeader("Content-Length", catalog.CatalogFile.Length.ToString());
context.Response.AddHeader("Content-disposition", "attachment;filename=" + fileName);
context.Response.BinaryWrite(fileArray);
// end the response
context.Response.Flush();
context.Response.Clear();
context.Response.Close();
context.Response.End();
希望这有帮助
亲切的问候
Hope this helps
Kind Regards
这篇关于使用C#从ASP.NET中的数据库中重写pfd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!