首页 > 解决方案 > 从 Asp.net Web Api 控制器获取文件名

问题描述

我有一个 Web Api 控制器,它获取文件。(服务器)

[HttpGet]
    [Route("api/FileDownloading/download")]
    public HttpResponseMessage GetDocuments()
    {
        var result = new HttpResponseMessage(HttpStatusCode.OK);

        var fileName = "QRimage2.jpg";
        var filePath = HttpContext.Current.Server.MapPath("");
        var fileBytes = File.ReadAllBytes(@"c:\\TMP\\QRimage2.jpg");
        MemoryStream fileMemStream = new MemoryStream(fileBytes);

        result.Content = new StreamContent(fileMemStream);

        var headers = result.Content.Headers;

        headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

        headers.ContentDisposition.FileName = fileName;

        headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        headers.ContentLength = fileMemStream.Length;

        return result;
    }

和 Xamarin Android 客户端,使用控制器下载文件(http://localhost:6100/api/FileDownloading/download

public void DownloadFile(string url, string folder)
    {
        string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder);
        Directory.CreateDirectory(pathToNewFolder);

        try
        {
            WebClient webClient = new WebClient();
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
            string pathToNewFile = Path.Combine(pathToNewFolder, Path.GetFileName(url));
            webClient.DownloadFileAsync(new Uri(url), null);
        }
        catch (Exception ex)
        {
            if (OnFileDownloaded != null)
                OnFileDownloaded.Invoke(this, new DownloadEventArgs(false));
        }
    }

一切正常,但在我的 Android 设备上的文件资源管理器中,我的文件名为“下载”而不是“QRimage2.jpg”。如何使用此控制器获取实际文件名?

标签: c#xamarinasp.net-web-api2

解决方案


您将需要使用 Web 响应来阅读内容配置。所以,我们不能直接使用 DownloadFileAsync。

public async Task<string> DownloadFileAsync(string url, string folder)
{
    var request = WebRequest.Create(url);
    var response = await request.GetResponseAsync().ConfigureAwait(false);
    var fileName = string.Empty;

    if (response.Headers["Content-Disposition"] != null)
    {
        var contentDisposition = new System.Net.Mime.ContentDisposition(response.Headers["Content-Disposition"]);

        if (contentDisposition.DispositionType == "attachment")
        {
            fileName = contentDisposition.FileName;
        }
    }

    if (string.IsNullOrEmpty(fileName))
    {
        throw new ArgumentException("Cannot be null or empty.", nameof(fileName));
    }

    var filePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder, fileName);

    using (var contentStream = response.GetResponseStream())
    {
        using (var fileStream = File.Create(filePath))
        {
            await contentStream.CopyToAsync(fileStream).ConfigureAwait(false);
        }
    }

    return filePath;
}

推荐阅读