簡體   English   中英

從Asp.net Web Api控制器獲取文件名

[英]Get file name from Asp.net Web Api controller

我有一個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”。 如何使用此控制器獲取實際的文件名?

這總是會是jpg嗎? 如果是這樣,我將MediaTypeHeaderValue更改為image/jpeg通過這樣做,您是在告訴瀏覽器文件的確切類型,而不是通用文件。 我想這是個問題,因為您告訴Android瀏覽器它只是一個通用二進制文件。

我需要Content-Type:application / octet-stream來下載文件嗎?

您將需要使用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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM