62 lines
2.1 KiB
C#
62 lines
2.1 KiB
C#
using iFileProxy.Models;
|
|
using System.Net.Http.Headers;
|
|
using System.Text.Json;
|
|
|
|
namespace iFileProxy.Helpers
|
|
{
|
|
public class FileDownloadHelper
|
|
{
|
|
|
|
public static DownloadFileInfo GetDownloadFileInfo(string url)
|
|
{
|
|
var fileInfo = new DownloadFileInfo();
|
|
var _httpClient = new HttpClient();
|
|
using (var request = new HttpRequestMessage(HttpMethod.Head, url))
|
|
{
|
|
using (var response = _httpClient.Send(request))
|
|
{
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
// 获取文件大小
|
|
if (response.Content.Headers.TryGetValues("Content-Length", out var values))
|
|
{
|
|
if (long.TryParse(values.First(), out long fileSize))
|
|
{
|
|
fileInfo.Size = fileSize;
|
|
}
|
|
else
|
|
fileInfo.Size = -1;
|
|
}
|
|
else
|
|
fileInfo.Size = -1;
|
|
|
|
// 获取文件名,优先从 Content-Disposition 中提取,如果没有再从 URL 提取
|
|
fileInfo.FileName = ExtractFileNameFromContentDisposition(response.Content.Headers.ContentDisposition)
|
|
?? ExtractFileNameFromUrl(url);
|
|
}
|
|
}
|
|
|
|
return fileInfo;
|
|
}
|
|
|
|
private static string ExtractFileNameFromContentDisposition(ContentDispositionHeaderValue contentDisposition)
|
|
{
|
|
if (contentDisposition != null)
|
|
{
|
|
// 检查是否有文件名
|
|
var fileName = contentDisposition.FileName ?? contentDisposition.FileNameStar;
|
|
return fileName;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private static string ExtractFileNameFromUrl(string url)
|
|
{
|
|
// 从 URL 中提取文件名,通常是 URL 路径的最后一部分
|
|
Uri uri = new Uri(url);
|
|
string fileName = Path.GetFileName(uri.LocalPath);
|
|
return fileName;
|
|
}
|
|
|
|
}
|
|
}
|