using SnapshotWinFormsApp.Entities.NewHotline; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using File = SnapshotWinFormsApp.Entities.NewHotline.File; namespace SnapshotWinFormsApp.Tools; public class FileTools { /// /// 下载网络文件并上传到文件服务器, 返回 File.Id /// /// /// /// public async Task GetNetworkFileAsync(string file, CancellationToken cancellationToken = default) { try { var fileBytes = await DownloadFileToMemoryAsync(file); if (fileBytes is null) return new FileJson(); var uploadUrl = ConfigurationManager.AppSettings["FileServerUrl"] + "/file/upload?source=hotline"; var match = Regex.Match(file, "[^/]+\\.[a-zA-Z0-9]+$").Value; var resultJson = await UploadFileFromMemoryAsync(fileBytes, match, uploadUrl); var result = resultJson.FromJson>(); var fileSplit = match.Split('.'); var entity = new File() { Additions = result.Result.Id, FileName = result.Result.FileName, Path = result.Result.Path, AllPath = file, Type = fileSplit[1], Name = fileSplit[0], }; return result.Result; } catch (Exception e) { var message = $"下载网络文件并上传到文件服务器失败: {e.Message}"; } return new FileJson(); } /// /// 下载文件, 返回字节 /// /// /// private async Task DownloadFileToMemoryAsync(string url) { try { using var client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsByteArrayAsync(); } catch (Exception e) { var msg = e.Message; } finally { } return null; } public async Task UploadFileFromMemoryAsync(byte[] fileBytes, string fileName, string uploadUrl) { using HttpClient client = new HttpClient(); using var multipartContent = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(fileBytes); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); multipartContent.Add(fileContent, "fileData", fileName); HttpResponseMessage response = await client.PostAsync(uploadUrl, multipartContent); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync(); return result; } }