1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- 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
- {
- /// <summary>
- /// 下载网络文件并上传到文件服务器, 返回 File.Id
- /// </summary>
- /// <param name="file"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- public async Task<FileJson> 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<ApiResponse<FileJson>>();
- 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();
- }
- /// <summary>
- /// 下载文件, 返回字节
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- private async Task<byte[]> 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<string> 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;
- }
- }
|