【问题标题】:Get file name from Asp.net Web Api controller从 Asp.net Web Api 控制器获取文件名
【发布时间】:2019-02-26 14:57:51
【问题描述】:

我有一个获取文件的 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# xamarin asp.net-web-api2


    【解决方案1】:

    您将需要使用网络响应来阅读内容配置。所以,我们不能直接使用 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;
    }
    

    【讨论】:

      【解决方案2】:

      这总是 jpg 吗?如果是这样,我会将 MediaTypeHeaderValue 更改为 image/jpeg - 通过这样做,您将告诉浏览器文件的确切类型,而不是通用文件。我认为这是问题所在,因为您告诉 Android 浏览器它只是一个通用二进制文件。

      Do I need Content-Type: application/octet-stream for file download?

      【讨论】:

      • 可以是任何类型。
      猜你喜欢
      • 2013-10-30
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      相关资源
      最近更新 更多