Fix downloadFile
This commit is contained in:
@@ -1,9 +1,10 @@
|
||||
using salesbook.Shared.Core.Dto;
|
||||
using salesbook.Maui.Core.Interface;
|
||||
using salesbook.Shared.Core.Dto;
|
||||
using salesbook.Shared.Core.Interface;
|
||||
|
||||
namespace salesbook.Maui.Core.Services;
|
||||
|
||||
public class AttachedService : IAttachedService
|
||||
public class AttachedService(IFilePreviewService filePreviewService) : IAttachedService
|
||||
{
|
||||
public async Task<AttachedDTO?> SelectImageFromCamera()
|
||||
{
|
||||
@@ -95,48 +96,34 @@ public class AttachedService : IAttachedService
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<string?> SaveToTempStorage(Stream file, string fileName)
|
||||
public async Task<string> SaveToTempStorage(Stream file, string fileName, CancellationToken ct = default)
|
||||
{
|
||||
var cacheDirectory = FileSystem.CacheDirectory;
|
||||
var targetDirectory = Path.Combine(cacheDirectory, "file");
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
|
||||
if (!Directory.Exists(targetDirectory)) Directory.CreateDirectory(targetDirectory);
|
||||
if (file.CanSeek)
|
||||
file.Position = 0;
|
||||
|
||||
var tempFilePath = Path.Combine(targetDirectory, fileName + ".temp");
|
||||
var filePath = Path.Combine(targetDirectory, fileName);
|
||||
fileName = Path.GetFileName(fileName);
|
||||
|
||||
if (File.Exists(filePath)) return filePath;
|
||||
var dir = FileSystem.CacheDirectory;
|
||||
var filePath = Path.Combine(dir, fileName);
|
||||
|
||||
try
|
||||
{
|
||||
await using var fileStream =
|
||||
new FileStream(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||
await file.CopyToAsync(fileStream);
|
||||
|
||||
File.Move(tempFilePath, filePath);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"Errore durante il salvataggio dello stream: {e.Message}");
|
||||
SentrySdk.CaptureException(e);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(tempFilePath)) File.Delete(tempFilePath);
|
||||
}
|
||||
await using var fileStream = File.Create(filePath);
|
||||
await file.CopyToAsync(fileStream, ct);
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public async Task OpenFile(Stream file, string fileName)
|
||||
public Task OpenFile(string fileName, string filePath)
|
||||
{
|
||||
var filePath = await SaveToTempStorage(file, fileName);
|
||||
|
||||
if (filePath is null) return;
|
||||
await Launcher.OpenAsync(new OpenFileRequest
|
||||
#if IOS
|
||||
return filePreviewService.Preview(fileName, filePath);
|
||||
#else
|
||||
return Launcher.OpenAsync(new OpenFileRequest
|
||||
{
|
||||
Title = "Apri file",
|
||||
File = new ReadOnlyFile(filePath)
|
||||
});
|
||||
#endif
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user