c# - 从 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”。如何使用此控制器获取实际文件名?
解决方案
您将需要使用 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;
}
推荐阅读
- arduino - Arduino ESP8266 不读取 JSON 文件
- javascript - 返回json时使用模板文字?节点.js
- c# - 应该在另一个任务中使用 Task.Run 吗?
- python - 如何找到numpy数组的中心点?
- archlinux - Arch Linux 显示带有 xfce4 环境的白色终端
- javascript - 通过从数组创建单独的列表来制作具有不同材料类型的单独材料列表
- php - 如何刷新特定的用户会话
- node.js - 两个模型之间的 Mongoose 聚合
- laravel - 警告:require_once(bootstrap/app.php):打开流失败:C:\laragon\www\halfproject\public\index.php 中没有这样的文件或目录
- react-native - 如何确定在本机反应中获取数据的时间