pictureServer/PictureFilesApi/Services/PlatformServices.cs

1155 lines
43 KiB
C#
Raw Permalink Normal View History

2026-03-10 09:04:34 +08:00
using Hopetry.WebApi.Common;
using Infrastructure;
using Infrastructure.Extensions;
using Infrastructure.Helpers;
using MetadataExtractor;
using MetadataExtractor.Formats.Exif;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PictureFilesApi.Common;
using PictureFilesApi.Models;
using PictureFilesApi.Models.RequestModel;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Directory = System.IO.Directory;
namespace PictureFilesApi.Services
{
public class PlatformServices
{
IConfiguration _configuration;
private readonly ILogger<PlatformServices> _logger;
private string _filePath;
private readonly HttpClient _client;
//private string _dbFilePath; //数据库中的文件路径
//private string _dbThumbnail; //数据库中的缩略图路径
public PlatformServices(IConfiguration configuration, ILogger<PlatformServices> logger)
{
_configuration = configuration;
_logger = logger;
_filePath = AppContext.BaseDirectory;
var baseAddress = _configuration.GetSection("AppSetting:HttpHost").Value;
_client = new HttpClient
{
BaseAddress = new Uri(baseAddress)
};
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
public List<UploadFile> Upload(IFormFileCollection files, AddOrUpdateUploadReq req)
{
var result = new List<UploadFile>();
foreach (var file in files)
{
result.Add(Add(file, req));
}
return result;
}
/// <summary>
/// 上传文件-带备注
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
public async Task<List<UploadFile>> UploadWithExif(IFormFileCollection files, AddOrUpdateUploadReq req)
{
var fileresult = new List<UploadFile>();
var exifresult = new List<DroneImageRef>();
foreach (var file in files)
{
string extension = Path.GetExtension(file.FileName).ToLower();
if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp" ||
extension == ".gif")
{
var result = AddWithExif(file, req);
fileresult.Add(result.Item1);
if (result.Item2 != null && !string.IsNullOrEmpty(result.Item2.CaseId))
{
exifresult.Add(result.Item2);
}
}
else
{
fileresult.Add(Add(file, req));
}
}
if (exifresult.Count > 0)
{
var jsonData = JsonConvert.SerializeObject(exifresult);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsync("/api/DroneCaseInfoSingle/AddCaseImg", content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
}
return fileresult;
}
/// <summary>
/// 删除文件
/// </summary>
/// <returns></returns>
public Response<bool> DeleteImg(string path)
{
try
{
File.Delete(path);
_logger.LogError("删除文件成功:" + path);
return new Response<bool>
{
Result = true
};
}
catch (Exception ex)
{
_logger.LogError("删除文件失败:" + path);
return new Response<bool>
{
Result = false
};
}
}
/// <summary>
/// 判断图片是否存在
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public Response<bool> ExistsImg(string path)
{
try
{
if (File.Exists(path))
return new Response<bool> { Result = true };
else
{
return new Response<bool> { Result = false };
}
}
catch (Exception ex)
{
return new Response<bool>
{
Result = false
};
}
}
/// <summary>
/// 复制图片
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public Response<string> CopyImg(string sourceFilePathall)
{
string destinationFolder = "DroneEnforcement\\2024\\20240914";
string[] sourceFilePathsp = sourceFilePathall.Split(',');
string endSte = "";
foreach (var sourceFilePath in sourceFilePathsp)
{
try
{
// 检查源文件是否存在
if (!File.Exists(sourceFilePath))
{
continue;
}
// 获取源文件的文件名
string fileName = Path.GetFileName(sourceFilePath);
// 生成目标文件路径
string destFilePath = Path.Combine(destinationFolder, fileName);
// 复制文件到目标文件夹
File.Copy(sourceFilePath, destFilePath);
//endSte += destFilePath + ",";
endSte = destFilePath;
}
catch (Exception ex)
{
}
}
return new Response<string>
{
Result = endSte
};
}
public List<UploadFile> UploadNoReName(IFormFileCollection files, AddOrUpdateUploadReq req)
{
var result = new List<UploadFile>();
foreach (var file in files)
{
result.Add(Add(file, req, false));
}
return result;
}
/// <summary>
/// 单个添加文件
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public UploadFile Add(IFormFile file, AddOrUpdateUploadReq req, bool reName = false)
{
if (file != null && file.Length > 0 && file.Length < 104857600 * 2)
{
using (var binaryReader = new BinaryReader(file.OpenReadStream()))
{
var fileName = Path.GetFileName(file.FileName);
var data = binaryReader.ReadBytes((int)file.Length);
var tuple = SaveFile(fileName, data, req, reName);
string _dbFilePath = tuple.Item1;
string _dbThumbnail = tuple.Item2;
var filedb = new UploadFile
{
FilePath = _dbFilePath,
Thumbnail = _dbThumbnail,
FileName = fileName,
CreateTime = DateTime.Now,
FileSize = file.Length.ToInt(),
FileType = Path.GetExtension(fileName),
Extension = Path.GetExtension(fileName)
};
return filedb;
}
}
else
{
throw new Exception("文件过大");
}
}
/// <summary>
/// 单个添加文件-带备注
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public (UploadFile, DroneImageRef) AddWithExif(IFormFile file, AddOrUpdateUploadReq req, bool reName = false)
{
if (file != null && file.Length > 0 && file.Length < 104857600 * 2)
{
using (var binaryReader = new BinaryReader(file.OpenReadStream()))
{
var fileName = Path.GetFileName(file.FileName);
var data = binaryReader.ReadBytes((int)file.Length);
var tuple = SaveFile(fileName, data, req, reName);
string _dbFilePath = tuple.Item1;
string _dbThumbnail = tuple.Item2;
var filedb = new UploadFile
{
FilePath = _dbFilePath,
Thumbnail = _dbThumbnail,
FileName = fileName,
CreateTime = DateTime.Now,
FileSize = file.Length.ToInt(),
FileType = Path.GetExtension(fileName),
Extension = Path.GetExtension(fileName)
};
var exif = new DroneImageRef();
using (MemoryStream memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
memoryStream.Position = 0;
// 从文件流中读取元数据
var directories = ImageMetadataReader.ReadMetadata(memoryStream);
if (directories != null)
{
//备注 案件id
var exDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
if (exDirectory != null)
{
exif.Id = Guid.NewGuid().ToString();
exif.FilePath = filedb.FilePath;
var caseid = exDirectory.GetDescription(ExifSubIfdDirectory.TagUserComment);
exif.CaseId = caseid;
}
else
{
return (filedb, exif);
}
//经度
var gpsDirectory = directories.OfType<GpsDirectory>().FirstOrDefault();
if (gpsDirectory != null)
{
var latitude = gpsDirectory.GetDescription(GpsDirectory.TagLatitude);
var latitudeRef = gpsDirectory.GetDescription(GpsDirectory.TagLatitudeRef);
var longitude = gpsDirectory.GetDescription(GpsDirectory.TagLongitude);
var longitudeRef = gpsDirectory.GetDescription(GpsDirectory.TagLongitudeRef);
double latitudeDecimal = ConvertDmsToDecimal(latitude, latitudeRef);
double longitudeDecimal = ConvertDmsToDecimal(longitude, longitudeRef);
exif.Lat = latitudeDecimal;
exif.Lng = longitudeDecimal;
}
//方位角 Orientation
// 查找 EXIF IFD0 目录
var exifIfd0Directory = directories.OfType<ExifIfd0Directory>().FirstOrDefault();
if (exifIfd0Directory != null &&
exifIfd0Directory.TryGetInt32(ExifDirectoryBase.TagOrientation, out int orientation))
{
exif.Orientation = orientation;
}
//创建时间
var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
if (subIfdDirectory != null &&
subIfdDirectory.TryGetDateTime(ExifDirectoryBase.TagDateTimeOriginal,
out DateTime dateTime))
{
exif.CreateTime = dateTime;
}
else
{
exif.CreateTime = DateTime.Now;
}
}
}
return (filedb, exif);
}
}
else
{
throw new Exception("文件过大");
}
}
static double ConvertDmsToDecimal(string dmsString, string refString)
{
if (string.IsNullOrWhiteSpace(dmsString))
return double.NaN;
var parts = dmsString.Split('°', '\'', '\"');
if (parts.Length < 3)
return double.NaN;
try
{
double degrees = double.Parse(parts[0].Trim());
double minutes = double.Parse(parts[1].Trim());
double seconds = double.Parse(parts[2].Trim());
// Convert to decimal degrees
double decimalDegrees = degrees + (minutes / 60) + (seconds / 3600);
// Check the reference direction
if (refString == "S" || refString == "W")
decimalDegrees = -decimalDegrees;
return decimalDegrees;
}
catch (Exception)
{
// Handle parsing errors
return double.NaN;
}
}
/// <summary>
/// 存储文件,如果是图片文件则生成缩略图
/// </summary>
/// <param name="fileName"></param>
/// <param name="fileBuffers"></param>
/// <exception cref="Exception"></exception>
private Tuple<string, string> SaveFile(string fileName, byte[] fileBuffers, AddOrUpdateUploadReq req,
bool reName = true)
{
//string folder = req.project + "\\" + DateTime.Now.ToString("yyyy") + "\\" +
// DateTime.Now.ToString("yyyyMMdd");
//string folder_s = folder.Replace(req.project, "S_" + req.project);
string folder = Path.Combine(req.project, DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("yyyyMMdd"));
string folder_s = Path.Combine("S_" + req.project, DateTime.Now.ToString("yyyy"),
DateTime.Now.ToString("yyyyMMdd"));
2026-03-10 09:04:34 +08:00
//判断文件是否为空
if (string.IsNullOrEmpty(fileName))
{
throw new Exception("文件名不能为空");
}
//判断文件是否为空
if (fileBuffers.Length < 1)
{
throw new Exception("文件不能为空");
}
var uploadPath = Path.Combine(_filePath, folder);
var uploadPath_s = Path.Combine(_filePath, folder_s);
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
var ext = Path.GetExtension(fileName).ToLower();
// 获取文件名(不含扩展名)
string originalFileName = Path.GetFileNameWithoutExtension(fileName);
//判断是否存在相同文件名的文件
int count = 1;
while (File.Exists(Path.Combine(uploadPath, fileName)))
{
fileName = $"{originalFileName}_{count++}{ext}";
}
string newName = reName == true
? GenerateId.GenerateOrderNumber() + ext
: Path.GetFileNameWithoutExtension(fileName) + ext;
string _dbThumbnail = string.Empty;
string _dbFilePath = string.Empty;
using (var fs = new FileStream(Path.Combine(uploadPath, newName), FileMode.Create))
{
fs.Write(fileBuffers, 0, fileBuffers.Length);
fs.Close();
//生成缩略图
if (ext.Contains(".jpg") || ext.Contains(".jpeg") || ext.Contains(".png") || ext.Contains(".bmp") ||
ext.Contains(".gif"))
{
if (!Directory.Exists(uploadPath_s))
{
Directory.CreateDirectory(uploadPath_s);
}
//string thumbnailName = GenerateId.GenerateOrderNumber() + ext;
ImgHelper.MakeThumbnail(Path.Combine(uploadPath, newName), Path.Combine(uploadPath_s, newName));
_dbThumbnail = Path.Combine(folder_s, newName);
}
_dbFilePath = Path.Combine(folder, newName);
}
return new Tuple<string, string>(_dbFilePath, _dbThumbnail);
}
/// <summary>
/// 存储文件,如果是图片文件则生成缩略图 保留文件原始名 这个是给文件单独生成文件夹
/// </summary>
/// <param name="fileName"></param>
/// <param name="fileBuffers"></param>
/// <param name="req"></param>
/// <param name="reName"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private Tuple<string, string> SaveFileNew(string fileName, byte[] fileBuffers, AddOrUpdateUploadReq req,
bool reName = true)
{
string folder = req.project + "\\" + DateTime.Now.ToString("yyyy") + "\\" +
DateTime.Now.ToString("yyyyMMdd");
string folder_s = folder.Replace(req.project, "S_" + req.project);
//判断文件是否为空
if (string.IsNullOrEmpty(fileName))
{
throw new Exception("文件名不能为空");
}
//判断文件是否为空
if (fileBuffers.Length < 1)
{
throw new Exception("文件不能为空");
}
// 获取文件扩展名
var ext = Path.GetExtension(fileName).ToLower();
// 获取文件名(不含扩展名)
string originalFileName = Path.GetFileNameWithoutExtension(fileName);
string newName = originalFileName + ext;
// 组合文件夹路径
var uploadPath = Path.Combine(_filePath, folder, originalFileName);
var uploadPath_s = Path.Combine(_filePath, folder_s, originalFileName);
// 如果文件夹不存在,则创建
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
// 检查文件是否重名,如果重名则在文件名后添加 "_1", "_2" 等
int count = 1;
string tempFileName = newName;
while (File.Exists(Path.Combine(uploadPath, tempFileName)))
{
tempFileName = $"{originalFileName}_{count++}{ext}";
}
newName = tempFileName;
string _dbThumbnail = string.Empty;
string _dbFilePath = string.Empty;
// 保存文件
using (var fs = new FileStream(Path.Combine(uploadPath, newName), FileMode.Create))
{
fs.Write(fileBuffers, 0, fileBuffers.Length);
fs.Close();
// 如果是图像文件,生成缩略图
if (ext.Contains(".jpg") || ext.Contains(".jpeg") || ext.Contains(".png") || ext.Contains(".bmp") ||
ext.Contains(".gif"))
{
if (!Directory.Exists(uploadPath_s))
{
Directory.CreateDirectory(uploadPath_s);
}
ImgHelper.MakeThumbnail(Path.Combine(uploadPath, newName), Path.Combine(uploadPath_s, newName));
_dbThumbnail = Path.Combine(folder_s, originalFileName, newName);
}
_dbFilePath = Path.Combine(folder, originalFileName, newName);
}
return new Tuple<string, string>(_dbFilePath, _dbThumbnail);
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
public List<UploadFile> UploadGraph(IFormFileCollection files, AddOrUpdateUploadGraphReq req)
{
var result = new List<UploadFile>();
foreach (var file in files)
{
result.Add(AddGraph(file, req));
}
return result;
}
/// <summary>
/// 单个添加文件
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public UploadFile AddGraph(IFormFile file, AddOrUpdateUploadGraphReq req)
{
if (file != null && file.Length > 0 && file.Length < 104857600)
{
using (var binaryReader = new BinaryReader(file.OpenReadStream()))
{
var fileName = Path.GetFileName(file.FileName);
var data = binaryReader.ReadBytes((int)file.Length);
var tuple = SaveFileGraph(fileName, data, req);
string _dbFilePath = tuple.Item1;
string _dbThumbnail = tuple.Item2;
var filedb = new UploadFile
{
FilePath = _dbFilePath,
Thumbnail = _dbThumbnail,
FileName = fileName,
FileSize = file.Length.ToInt(),
FileType = Path.GetExtension(fileName),
Extension = Path.GetExtension(fileName)
};
return filedb;
}
}
else
{
throw new Exception("文件过大");
}
}
/// <summary>
/// 保存带水印的图片
/// </summary>
/// <param name="fileName"></param>
/// <param name="fileBuffers"></param>
private Tuple<string, string> SaveFileGraph(string fileName, byte[] fileBuffers, AddOrUpdateUploadGraphReq req)
{
string folder = req.project + "\\" + DateTime.Now.ToString("yyyy") + "\\" +
DateTime.Now.ToString("yyyyMMdd");
string folder_s = folder.Replace(req.project, "S_" + req.project);
//判断文件是否为空
if (string.IsNullOrEmpty(fileName))
{
throw new Exception("文件名不能为空");
}
//判断文件是否为空
if (fileBuffers.Length < 1)
{
throw new Exception("文件不能为空");
}
var uploadPath = Path.Combine(_filePath, folder);
var uploadPath_s = Path.Combine(_filePath, folder_s);
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
var ext = Path.GetExtension(fileName).ToLower();
string newName = GenerateId.GenerateOrderNumber() + ext;
string _dbThumbnail = string.Empty;
string _dbFilePath = string.Empty;
if (req.haveFileName == 1)
{
req.watermark += "\n" + newName;
}
if (req.haveDateTime == 1)
{
req.watermark += "\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
//画笔画图画水印并保存
PutGraphics(fileBuffers, Path.Combine(uploadPath, newName), req);
//生成缩略图
if (ext.Contains(".jpg") || ext.Contains(".jpeg") || ext.Contains(".png") || ext.Contains(".bmp") ||
ext.Contains(".gif"))
{
if (!Directory.Exists(uploadPath_s))
{
Directory.CreateDirectory(uploadPath_s);
}
//string thumbnailName = GenerateId.GenerateOrderNumber() + ext;
ImgHelper.MakeThumbnail(Path.Combine(uploadPath, newName), Path.Combine(uploadPath_s, newName));
_dbThumbnail = Path.Combine(folder_s, newName);
}
_dbFilePath = Path.Combine(folder, newName);
return new Tuple<string, string>(_dbFilePath, _dbThumbnail);
}
private bool PutGraphics(byte[] bytes, string path, AddOrUpdateUploadGraphReq req)
{
try
{
var watermarkedStream = new MemoryStream();
//return BytToImg(bytes);
using (var image = BytToImg(bytes))
{
Graphics g = Graphics.FromImage(image);
Font font = new Font(FontFamily.GenericSerif, 20, FontStyle.Regular);
Color color = Color.Red;
if (req.color == "white")
{
color = Color.White;
}
SolidBrush brush = new SolidBrush(color);
SizeF size = g.MeasureString(req.watermark, font); //文字显示的尺寸
var top = (image.Height - size.Height);
var left = 0;
g.DrawString(req.watermark, font, brush, left, top);
g.Dispose();
GC.Collect();
//这句必须放在下边如果放在返回值中会报错应该和GC回收机制有关
//image.Save(path, ImageFormat.Png);
ImageHelper.Compress((Bitmap)image, path, 50);
return true;
}
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 字节流转换成图片
/// </summary>
/// <param name="byt">要转换的字节流</param>
/// <returns>转换得到的Image对象</returns>
public Image BytToImg(byte[] byt)
{
MemoryStream ms = new MemoryStream(byt);
Image img = Image.FromStream(ms);
return img;
}
/// <summary>
/// 下载图片接口
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public string DownLoadPictures(QueryDownLoadPicturesReq req)
{
string root = AppDomain.CurrentDomain.BaseDirectory;
string downLoadPath = "DownLoadFiles\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
string directoryPath = downLoadPath + Guid.NewGuid().ToString() + "\\";
if (!Directory.Exists(root + directoryPath))
{
Directory.CreateDirectory(root + directoryPath);
}
for (int i = 0; i < req.files.Length; i++)
{
string filePath = req.files[i];
string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
if (File.Exists(root + filePath))
{
File.Copy(root + filePath, root + directoryPath + fileName);
}
}
if (File.Exists(root + downLoadPath + req.filename + ".zip"))
{
File.Delete(root + downLoadPath + req.filename + ".zip");
}
ZipFile.CreateFromDirectory(root + directoryPath, root + downLoadPath + req.filename + ".zip",
CompressionLevel.Optimal, false);
Task.Run(() =>
{
Thread.Sleep(1000 * 60 * 10);
//为了防止误删,判断路径是否有 DownLoadFiles
if ((root + directoryPath).IndexOf("DownLoadFiles") >= 0)
{
//删除拷贝过来的图片
Directory.Delete(root + directoryPath, true);
}
//为了防止误删,判断路径是否有 DownLoadFiles
if ((root + downLoadPath + req.filename + ".zip").IndexOf("DownLoadFiles") >= 0)
{
//删除打包后的压缩包
File.Delete(root + downLoadPath + req.filename + ".zip");
}
});
return downLoadPath + req.filename + ".zip";
}
/// <summary>
/// 下载网络图片到本地路径
/// </summary>
/// <returns></returns>
public string DownLoadInternetToLocal(AddOrUpdateDownLoadInternetToLocalReq req)
{
//根目录
string root = AppDomain.CurrentDomain.BaseDirectory;
//遍历所有图片路径
for (int i = 0; i < req.files.Count; i++)
{
var _item = req.files[i];
//判断是否存在此文件
string fullPath = root + _item;
string smallFullPath = root + "S_" + _item;
if (!File.Exists(fullPath))
{
//从这里下载图片到指定路径
//设置10秒超时时间
var flag = HttpClientHelper.DownloadPicture(req.uri, _item, 10 * 1000);
}
if (!File.Exists(smallFullPath))
{
//从这里下载图片的缩略图到指定路径
//设置10秒超时时间
var flag = HttpClientHelper.DownloadPicture(req.uri, "S_" + _item, 10 * 1000);
}
}
return "下载完成";
}
public async Task<Response<bool>> UploadImagesold(List<StructuredFileDto> Files)
{
if (Files == null || Files.Count == 0)
{
return new Response<bool>
{
Code = 500,
Result = false,
Message = "未上传文件"
};
}
string root = AppDomain.CurrentDomain.BaseDirectory;
foreach (var fileDto in Files)
{
if (fileDto.File == null || fileDto.Metadata == null)
{
continue; // 跳过无效数据
}
string savePath = root + fileDto.Metadata.Path;
string directoryPath = savePath.Substring(0, savePath.LastIndexOf("\\") + 1);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
2026-03-10 09:04:34 +08:00
await using (var stream = new FileStream(savePath, FileMode.Create))
{
await fileDto.File.CopyToAsync(stream);
}
}
return new Response<bool>
{
Code = 200,
Result = true,
Message = "上传成功"
};
}
2026-03-10 09:04:34 +08:00
public async Task<Response<bool>> UploadImages(List<StructuredFileDto> Files)
{
if (Files == null || Files.Count == 0)
{
return new Response<bool>
{
Code = 500,
Result = false,
Message = "未上传文件"
};
}
string root = AppDomain.CurrentDomain.BaseDirectory;
foreach (var fileDto in Files)
{
if (fileDto.File == null || fileDto.Metadata == null)
{
continue;
}
2026-03-10 09:04:34 +08:00
// 把 Windows 路径转换为当前系统路径
string relativePath = fileDto.Metadata.Path
.Replace("\\", Path.DirectorySeparatorChar.ToString())
.Replace("/", Path.DirectorySeparatorChar.ToString());
// 组合路径(跨平台)
string savePath = Path.Combine(root, relativePath);
// 获取目录
string directoryPath = Path.GetDirectoryName(savePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
await using (var stream = new FileStream(savePath, FileMode.Create))
{
await fileDto.File.CopyToAsync(stream);
}
}
return new Response<bool>
{
Code = 200,
Result = true,
Message = "上传成功"
};
}
public async Task<Response<bool>> UploadImages1(IFormCollection form)
{
var files = form.Files;
var metadata = form["paths"]; // StringValues可当数组用
for (int i = 0; i < files.Count; i++)
{
var file = files[i];
var path = metadata.Count > i ? metadata[i] : file.FileName;
string savePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
Directory.CreateDirectory(Path.GetDirectoryName(savePath)!);
await using var stream = new FileStream(savePath, FileMode.Create);
await file.CopyToAsync(stream);
}
return new Response<bool>
{
Code = 200,
Result = true,
Message = "上传成功"
};
}
/// <summary>
/// 复制图片
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public async Task<List<UploadFile>> NewCopyImg(string sourceFilePathAll)
{
//DroneEnforcement\\2024\\20241109\\Image_Water_1731054661277_6.jpeg
// todo 无论是斜杠还是反斜杠都统一为斜杠 \\\\ 两个反斜杠 \\ 一个反斜杠
var sourceFilePathsp = sourceFilePathAll
.Replace("\\\\", "/")
.Replace("\\", "/")
.Split(',');
2026-03-10 09:04:34 +08:00
// DroneEnforcement
var suffix = sourceFilePathsp[0].Split('/')[0];
2026-03-10 09:04:34 +08:00
var fileResult = new List<UploadFile>();
// 不生成DroneImageRef信息因为案件信息不一样
var current = DateTime.Now;
//目录文件夹
var destinationFolder = suffix + "/" + current.ToString("yyyy") + "/" + current.ToString("yyyyMMdd");
foreach (var oldPath in sourceFilePathAll.Split(','))
2026-03-10 09:04:34 +08:00
{
var newPath = oldPath.Replace("\\\\", "/").Replace("\\", "/");
2026-03-10 09:04:34 +08:00
// 源文件绝对路径
var sourceFilePath = _filePath + "/" + newPath;
2026-03-10 09:04:34 +08:00
// 如果是文件,直接复制,如果是图片,还需要复制小图
try
{
// 检查源文件是否存在
if (!File.Exists(sourceFilePath))
{
continue;
}
// 获取源文件的文件名
var fileName = Path.GetFileName(sourceFilePath);
// 生成目标文件路径
var destFilePath = destinationFolder + "/" + fileName;
2026-03-10 09:04:34 +08:00
// 复制文件到目标文件夹
var absolutePath = _filePath + "/" + destFilePath;
2026-03-10 09:04:34 +08:00
if (!Directory.Exists(Path.GetDirectoryName(absolutePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(absolutePath));
}
else
{
// 获取文件名(不含扩展名)
var originalFileName = Path.GetFileNameWithoutExtension(sourceFilePath);
var ext = Path.GetExtension(sourceFilePath);
//判断是否存在相同文件名的文件
int count = 1;
while (File.Exists(absolutePath))
{
fileName = $"{originalFileName}_{count++}{ext}";
destFilePath = destinationFolder + "/" + fileName;
absolutePath = _filePath + "/" + destFilePath;
2026-03-10 09:04:34 +08:00
}
}
File.Copy(sourceFilePath, absolutePath);
var fileInfo = new FileInfo(absolutePath);
var temp = new UploadFile
{
FilePath = destFilePath,
FileName = fileName,
OriginalPath = oldPath,
2026-03-10 09:04:34 +08:00
CreateTime = DateTime.Now,
FileSize = fileInfo.Length.ToInt(),
FileType = Path.GetExtension(fileName),
Extension = Path.GetExtension(fileName)
};
// 文件已经保存,现在的工作是生成记录
var extension = Path.GetExtension(sourceFilePath);
if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp" ||
extension == ".gif")
{
var thumbnailSourceFilePath = _filePath + "/" + "S_" + newPath;
2026-03-10 09:04:34 +08:00
if (File.Exists(thumbnailSourceFilePath))
{
var thumbnailDestFilePath = _filePath + "/" + "S_" + destFilePath;
2026-03-10 09:04:34 +08:00
if (!Directory.Exists(Path.GetDirectoryName(thumbnailDestFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(thumbnailDestFilePath));
}
File.Copy(thumbnailSourceFilePath, thumbnailDestFilePath);
temp.Thumbnail = "S_" + destFilePath;
}
}
fileResult.Add(temp);
}
catch (Exception ex)
{
}
}
// 存储图片方位角等信息 这部分直接复制数据库里的数据
/*if (exifResult.Count > 0)
{
var jsonData = JsonConvert.SerializeObject(exifResult);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsync("/api/DroneCaseInfoSingle/AddCaseImg", content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
}*/
return fileResult;
}
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="destFilePath"></param>
/// <returns></returns>
private (UploadFile, DroneImageRef) AddWithExif1(string destFilePath)
{
var fileName = Path.GetFileName(destFilePath);
var file = File.OpenRead(destFilePath);
// DroneEnforcement\2024\20240731\2024073110155230280042.jpg
// todo 取出路径
// 生成缩略图
string folder_s = "S_DroneEnforcement\\" + DateTime.Now.ToString("yyyy") + "\\" +
DateTime.Now.ToString("yyyyMMdd");
var uploadPath_s = Path.Combine(_filePath, folder_s);
var ext = Path.GetExtension(fileName).ToLower();
string _dbThumbnail = string.Empty;
//生成缩略图
if (ext.Contains(".jpg") || ext.Contains(".jpeg") || ext.Contains(".png") || ext.Contains(".bmp") ||
ext.Contains(".gif"))
{
if (!Directory.Exists(uploadPath_s))
{
Directory.CreateDirectory(uploadPath_s);
}
//string thumbnailName = GenerateId.GenerateOrderNumber() + ext;
ImgHelper.MakeThumbnail(Path.Combine(_filePath, destFilePath), Path.Combine(uploadPath_s, fileName));
_dbThumbnail = Path.Combine(folder_s, fileName);
}
var fileDb = new UploadFile
{
FilePath = destFilePath,
Thumbnail = _dbThumbnail,
FileName = fileName,
CreateTime = DateTime.Now,
FileSize = file.Length.ToInt(),
FileType = Path.GetExtension(fileName),
Extension = Path.GetExtension(fileName)
};
var exif = new DroneImageRef();
using (MemoryStream memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
memoryStream.Position = 0;
// 从文件流中读取元数据
var directories = ImageMetadataReader.ReadMetadata(memoryStream);
if (directories != null)
{
//备注 案件id
var exDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
if (exDirectory != null)
{
exif.Id = Guid.NewGuid().ToString();
exif.FilePath = fileDb.FilePath;
var caseid = exDirectory.GetDescription(ExifSubIfdDirectory.TagUserComment);
exif.CaseId = caseid;
}
else
{
return (fileDb, exif);
}
//经度
var gpsDirectory = directories.OfType<GpsDirectory>().FirstOrDefault();
if (gpsDirectory != null)
{
var latitude = gpsDirectory.GetDescription(GpsDirectory.TagLatitude);
var latitudeRef = gpsDirectory.GetDescription(GpsDirectory.TagLatitudeRef);
var longitude = gpsDirectory.GetDescription(GpsDirectory.TagLongitude);
var longitudeRef = gpsDirectory.GetDescription(GpsDirectory.TagLongitudeRef);
double latitudeDecimal = ConvertDmsToDecimal(latitude, latitudeRef);
double longitudeDecimal = ConvertDmsToDecimal(longitude, longitudeRef);
exif.Lat = latitudeDecimal;
exif.Lng = longitudeDecimal;
}
//方位角 Orientation
// 查找 EXIF IFD0 目录
var exifIfd0Directory = directories.OfType<ExifIfd0Directory>().FirstOrDefault();
if (exifIfd0Directory != null &&
exifIfd0Directory.TryGetInt32(ExifDirectoryBase.TagOrientation, out int orientation))
{
exif.Orientation = orientation;
}
//创建时间
var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
if (subIfdDirectory != null && subIfdDirectory.TryGetDateTime(ExifDirectoryBase.TagDateTimeOriginal,
out DateTime dateTime))
{
exif.CreateTime = dateTime;
}
else
{
exif.CreateTime = DateTime.Now;
}
}
}
return (fileDb, exif);
}
}
}