3

场景是我有一个表单,它在提交时在模板上执行邮件合并并创建一个 word 文档,然后将其存储在 azure blob 存储中。

我的问题是我希望允许用户使用 Web Api 2 和自定义 IHttpActionResult 下载此文件

public class FileActionResult : IHttpActionResult
{
    private readonly HttpRequestMessage _request;
    private readonly StreamContent _content;
    private readonly MediaTypeHeaderValue _contentType;
    private readonly long? _contentLength;
    private readonly ContentDispositionHeaderValue _contentDisposition;

    public FileActionResult(HttpRequestMessage request, StreamContent content, MediaTypeHeaderValue contentType, 
        long? contentLength, 
        ContentDispositionHeaderValue contentDisposition)
    {
        _request = request;
        _content = content;
        _contentType = contentType;
        _contentLength = contentLength;
        _contentDisposition = contentDisposition;
    }


    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = _request.CreateResponse(HttpStatusCode.Accepted);
        response.Content = _content;
        response.Content.Headers.ContentLength = _contentLength;
        response.Content.Headers.ContentType = _contentType;
        response.Headers.CacheControl = new CacheControlHeaderValue();
        response.Content.Headers.ContentDisposition = _contentDisposition;

        return Task.FromResult(response);
    }
}

然后我的 Api 控制器有一个 GetFile 方法来检索文件。

[OverrideAuthentication]
    [AllowAnonymous]
    [HttpGet("GetFile")]
    public async Task<IHttpActionResult> GetFile(string fileName)
    {
        var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccountConnectionString"));
        var blobClient = storageAccount.CreateCloudBlobClient();
        var container = blobClient.GetContainerReference("MoveInn");
        var blob = await container.GetBlobReferenceFromServerAsync(@"http://xxxxxxxx.blob.core.windows.net/xxxxx/" + fileName);
        var blobExists = await blob.ExistsAsync();
        if (!blobExists)
        {
            return BadRequest("Not Found.");
        }


        var blobStream = await blob.OpenReadAsync();

        var result = new FileActionResult(Request,
            new StreamContent(blobStream),
            new MediaTypeHeaderValue(blob.Properties.ContentType), 
            blob.Properties.Length,
            new ContentDispositionHeaderValue("attachment"){
                FileName = fileName.Split('.')[1],
                Size = blob.Properties.Length
            });

        return result;
    }

这似乎在 chrome 中完美运行,但我在尝试在 IE10/11 中下载文件时遇到问题。出现询问您是要打开文件还是保存文件的对话框,但文件的文件名是整个Get Path,即GetFile?fileName=xxxxxxxxxxxxxxx.docx。

然后当我尝试保存此文件时,我无法保存。

任何帮助都会很棒!

4

0 回答 0