相关疑难解决方法(0)

ASP.NET MVC:如何让浏览器打开并显示PDF而不是显示下载提示?

好的,所以我有一个生成PDF并将其返回给浏览器的动作方法.问题是,IE不会自动打开PDF,而是显示下载提示,即使它知道它是什么类型的文件.Chrome做同样的事情.在这两种浏览器中,如果我单击指向存储在服务器上的PDF文件的链接,它将打开正常,并且永远不会显示下载提示.

以下是调用以返回PDF的代码:

public FileResult Report(int id)
{
    var customer = customersRepository.GetCustomer(id);
    if (customer != null)
    {
        return File(RenderPDF(this.ControllerContext, "~/Views/Forms/Report.aspx", customer), "application/pdf", "Report - Customer # " + id.ToString() + ".pdf");
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

这是服务器的响应头:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Thu, 16 Sep 2010 06:14:13 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 2.0
Content-Disposition: attachment; filename="Report - Customer # 60.pdf"
Cache-Control: private, s-maxage=0
Content-Type: application/pdf
Content-Length: 79244
Connection: Close
Run Code Online (Sandbox Code Playgroud)

我是否必须在响应中添加一些特殊内容才能让浏览器自动打开PDF?

任何帮助是极大的赞赏!谢谢!

pdf asp.net-mvc

40
推荐指数
2
解决办法
3万
查看次数

如何直接在浏览器中打开pdf文件?

我想PDF直接在浏览器中查看文件.我知道这个问题已经被问到了,但我找不到适用于我的解决方案.

到目前为止,这是我的动作控制器代码:

public ActionResult GetPdf(string fileName)
{
    string filePath = "~/Content/files/" + fileName;
    return File(filePath, "application/pdf", fileName);
}
Run Code Online (Sandbox Code Playgroud)

这是我的观点:

@{
   doc = "Mode_d'emploi.pdf";
} 

<p>@Html.ActionLink(UserResource.DocumentationLink, "GetPdf", "General", new { fileName = doc }, null)</p>
Run Code Online (Sandbox Code Playgroud)

当我鼠标悬停时,这里的链接是链接:

在此输入图像描述

我的代码的问题是pdf文件没有在浏览器中查看,但我收到一条消息,询问我是否打开或保存文件.

在此输入图像描述

我知道这是可能的,我的浏览器支持它,因为我已经用另一个网站测试它,允许我pdf直接在我的浏览器中查看.

例如,这是我鼠标悬停链接(在另一个网站上)时的链接:

在此输入图像描述

如您所见,生成的链接存在差异.我不知道这是否有用.

知道怎样才能pdf直接在浏览器中查看我的内容?

c# asp.net-mvc

19
推荐指数
3
解决办法
5万
查看次数

从.NET Core控制器返回CSV

我无法将.NET Core API Controller端点解析为CSV下载.我正在使用以下从.NET 4.5控制器中提取的代码:

[HttpGet]
[Route("{id:int}")]
public async Task<HttpResponseMessage> Get(int id)
{
    string csv = await reportManager.GetReport(CustomerId, id);
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StringContent(csv);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
    response.Content.Headers.ContentDisposition = 
        new ContentDispositionHeaderValue("attachment") { FileName = "report.csv" };
    return response;
}
Run Code Online (Sandbox Code Playgroud)

当我从Angular 4应用程序中点击此端点时,我将以下响应写入浏览器:

{
    "version": {
        "major": 1,
        "minor": 1,
        "build": -1,
        "revision": -1,
        "majorRevision": -1,
        "minorRevision": -1
    },
    "content": {
        "headers": [
            {
                "key": "Content-Type",
                "value": [
                    "text/csv"
                ]
            },
            {
                "key": "Content-Disposition",
                "value": [
                    "attachment; …
Run Code Online (Sandbox Code Playgroud)

c# csv asp.net asp.net-core

15
推荐指数
2
解决办法
2万
查看次数

如何使用MVC3 FileContentResult避免重复的内容处置标头?

我们有一些文件存储在sql数据库中.在ASP.NET MVC3表单上,我们显示2个链接:

查看此文件| 下载此文件

这些链接转到这些相应的操作方法.下载按预期工作 - 单击链接会强制在浏览器中保存对话框.但是,显示会导致重复的内容处置标头发送到浏览器,导致Chrome出错,Firefox中出现空白页面.

[ActionName("display-file")]
public virtual ActionResult DisplayFile (Guid fileId, string fileName)
{
    var file = _repos.GetFileInfo(fileId);
    if (file != null)
    {
        Response.AddHeader("Content-Disposition", 
            string.Format("inline; filename={0}", file.Name));
        return File(file.Content, file.MimeType, file.Name);
    }
}

[ActionName("download-file")]
public virtual ActionResult DownloadFile (Guid fileId, string fileName)
{
    var file = _repos.GetFileInfo(fileId);
    if (file != null)
    {
        return File(file.Content, file.MimeType, file.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是发送到浏览器以显示操作的2个标头:

Content-Disposition: inline; filename=name-of-my-file.pdf
Content-Disposition: attachment; filename="name-of-my-file.pdf"
Run Code Online (Sandbox Code Playgroud)

我尝试更改自定义内容处置标头以用双引号包装文件名,但它仍然向浏览器发送了2个标头.我还尝试在添加自定义标头之前删除Content-Disposition标头,但是在返回FileContentResult之后会出现附件标头.

这段代码以前有用.我昨天进行了测试,发现它已不再适用于Chrome或Firefox.这可能是由于浏览器的更新.IE8和Safari仍然正确打开文件.

更新

再次感谢达林,你是对的.我们实际使用这种方法是因为您回答另一个问题.

关于如何最终解决这个问题的更多信息,我们有一个显示文件链接的自定义路由:

context.MapRoute(null,
    "path/to/display-file-attachment/{fileId}/{fileName}",
    new …
Run Code Online (Sandbox Code Playgroud)

download content-disposition asp.net-mvc-3

12
推荐指数
1
解决办法
9515
查看次数

安全地在浏览器中下载具有正确文件名的文件

我正在一个网站上做一些工作,该网站有一个安全区域,只有在用户登录后才能使用.在这个区域有一个页面,其中包含可以下载的pdf文档的链接.物理文档位于Web站点的根目录之外.pdf文档的链接如下所示:

的index.php?页=安全区域/下载&文件= protected.pdf

它执行以下(注:我知道这是强制进行下载,而不是打开该文件的方式的浏览器):

// check security, get filename from request, prefix document download directory and check for file existance then...

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Connection: Close');
set_time_limit(0);
readfile($file);
Run Code Online (Sandbox Code Playgroud)

这很好用,但在Firefox 3和Internet Explorer 7(我没有使用任何其他浏览器进行测试)不会在浏览器中打开此文件,它们都显示下载对话框(如预期的那样).如果我选择"打开"而不是"保存",则会下载文档并在浏览器外部启动Adobe Reader以呈现文档.

我遇到的问题是在浏览器中下载文件并保存正确的默认文件名.

我想在浏览器中打开该文档.一种方法是使用标题"Content-Disposition:inline;" 但这意味着我无法指定文件名(因为浏览器似乎忽略了).这样做的问题是当我保存文档时,默认名称是URL的名称,而不是pdf文档的文件名:

http___example.com_index.php_page=secure_area_download&file=protected.pdf
Run Code Online (Sandbox Code Playgroud)

如何让Firefox和Internet Explorer在浏览器中打开文档并提供正确的默认文件名来保存?

browser security inline file download

4
推荐指数
1
解决办法
1万
查看次数

如何在MVC中的动作结果中返回PDF

我有点问题让我解决这个问题.我有一个ajax调用,应该呈现一个加载PDF的iframe.PDF是使用在其他环境中托管的Apache FOP生成的.到目前为止我所拥有的是:

在控制器动作中(iFrame指向的src元素),代码片段为:

var targetStream = new MemoryStream();    
using (var response = FOPrequest.GetResponse()) // response from FOP
                {
                    using (var stream = response.GetResponseStream())
                    {
                        stream.CopyTo(targetStream);

                    }
                }
 return new FileStreamResult(targetStream, "application/pdf");
Run Code Online (Sandbox Code Playgroud)

但是,这不能按预期工作.将按预期填充流,但PDF不会在iFrame中呈现.我得到一个Http响应代码200(OK).

我会感激任何帮助.

c# pdf ajax asp.net-mvc iframe

4
推荐指数
2
解决办法
2万
查看次数

使用ASP MVC下载并显示私有Azure Blob

我正在使用ASP MVC 5 Razor和Microsoft Azure Blob存储.我可以使用MVC成功地将文档和图像上传到Blob存储,但我很难找到一些MVC示例如何下载和显示文件.

如果将blob存储为公共文件,那么执行此操作将非常简单,但我需要它们是私有的.

任何人都可以给我任何实例或指导如何实现这一目标?

我在下面有一些代码似乎可以检索Blob,但我不知道如何在MVC中使用它来实际在浏览器中显示它.

var fullFileName = "file1.pdf";
var containerName = "default";

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AttachmentStorageConnection"].ConnectionString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);

// Retrieve reference to a blob ie "picture.jpg".
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fullFileName);
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc azure azure-storage-blobs razor

4
推荐指数
1
解决办法
4229
查看次数

如何在新选项卡或窗口中打开 PDF 文件而不是使用 C# 和 ASP.NET MVC 下载它?

我有发票屏幕,在此屏幕中有可用的订单数量,因此当我们创建发票时,我们需要填写一张表格,所以我想要的解决方案是当我提交此发票表格或单击此提交按钮时 pdf 应以新格式打开标签。我想向您澄清,我们不会将此 pdf 保存在任何地方。

<div class="modal-footer custom-no-top-border">
      <input type="submit" class="btn btn-primary" id="createdata" value="@T("Admin.Common.Create")" />
</div>
Run Code Online (Sandbox Code Playgroud)

当我单击此按钮时,pdf 应在新选项卡中打开。

这是pdf代码

 [HttpPost]
 public virtual ActionResult PdfInvoice(int customerOrderselectedId)
 {
        var customerOrder = _customerOrderService.GetCustomerOrderById(customerOrderselectedId);

        var customerOrders = new List<DD_CustomerOrder>();

        customerOrders.Add(customerOrder);
        byte[] bytes;

        using (var stream = new MemoryStream())
        {
            _customerOrderPdfService.PrintInvoicePdf(stream, customerOrders);
            bytes = stream.ToArray();
        }

        return File(bytes, MimeTypes.ApplicationPdf, string.Format("order_{0}.pdf", customerOrder.Id));
    }
Run Code Online (Sandbox Code Playgroud)

当我单击按钮时,此代码会下载 pdf。

谢谢 !!

c# pdf asp.net-mvc

3
推荐指数
1
解决办法
1万
查看次数

MVC 忽略某些路由上的 .jpg 文件扩展名——使用控制器操作?

我正在尝试从特定的 url 系统提供图像文件,如下所示:

mysite/Images/Category/File_Name.extension

我已经设置了这样的路线:

routes.MapRoute( "ImagesRoute", // Route name 
                 "Images/{category}/{file}.jpg", // URL with parameters 
                 new { controller = "Posts", 
                       action = "ViewImage", 
                       category = "", file = "" } // Parameter defaults 
                );
Run Code Online (Sandbox Code Playgroud)

哪个应该映射到我的控制器操作:

public ActionResult ViewImage(string category, string file)
    {
        var dir = Server.MapPath("/Images");
        var imgtitle = file.Replace("_", " ").Replace(".jpg", "");
        var repos = new BlogImagesRepository();
        var guid = repos.FetchImageByCategoryAndTitle(category, imgtitle);
        var path = Path.Combine(dir, category, guid.ImageGuid.ToString());
        return File(path, "image/jpeg");
    }
Run Code Online (Sandbox Code Playgroud)

如果我从路由中删除 .jpg 扩展名并请求在 url 上没有 .jpg 扩展名的文件标题(即:Images/MyCategory/My_Image)它显示得很好。但是,添加 …

model-view-controller file-extension jpeg routes asp.net-mvc-4

1
推荐指数
1
解决办法
2428
查看次数