防止IDM在web api中自动下载

时间:2017-03-29 07:53:34

标签: c# angularjs pdf asp.net-web-api

我有一个web api方法,它返回包含PDF文件的HttpResponseMessage。该方法如下所示:

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(path, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;

当我从客户端(用angularJS编写)调用此api时,Internet Download Manager会自动捕获PDF文件并想要下载它。因为我的项目有安全计划,IDM会自动请求用户名和密码。 有没有人知道我应该如何以编程方式阻止IDM捕获PDF文件?

更新:这是我的angularJS代码:

$http.post(url, { transactionId: txId }
            , {responseType: 'arraybuffer'})
            .success(function (response) {
                var reader = new FileReader();
                var file = new Blob([response.data], {type: 'application/pdf'});
                reader.onload = function (e) {
                    var printElem = angular.element('#printPdfLink');
                    printElem.attr('target', '_blank');
                    printElem.attr('href', reader.result);
                    printElem.attr('ng-click', '');
                };
                reader.readAsDataURL(file);
            })
            .error(function (error) {});

2 个答案:

答案 0 :(得分:8)

将mime类型更改为application/octet-stream,以解决您的问题。确保文件名包含正确的文件扩展名,以便下载后客户端系统可以识别它。

另一个问题是内容的attachment处置,通常会强制它将其保存为文件下载。将其更改为inline,以便客户端可以使用它而无需IDM尝试将其作为附件下载。

var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
var content new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
content.Headers.ContentDisposition.FileName = fileName;
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = content;
return response;

答案 1 :(得分:1)

我尝试使用HttpResponseMessage

如果我使用ContentDispositioninline,则响应会中断该文件。如果使用attachment,则IDM可以检测到它。

在一天结束时,我发现Accept-Ranges标题可以在没有IDM的情况下下载,但在HttpResponseMessage中无效。

您可以在下面试用我的代码来制作没有IDM的下载文件:

[HttpGet]
[Route("~/download/{filename}")]
public void Download(string filename)
{
    // TODO lookup file path by {filename}
    // If you want to have "." in {filename} you need enable in webconfig
    string filePath = "<path>"; // your file path here
    byte[] fileBytes = File.ReadAllBytes(filePath);
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("Accept-Ranges", "bytes");
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.AddHeader("ContentDisposition", "attachment, filename=" + filename);
    HttpContext.Current.Response.BinaryWrite(fileBytes);
    HttpContext.Current.Response.End();
}

注意:filename参数用于下载文件名,因此如果您想要文件扩展名(默认情况下已禁用),则可以在webconfig中进行配置。

相关问题