using System.Net.Http.Headers;
using System.Text.Json.Serialization;
namespace Elsa.Http;
///
/// Represents a downloadable object.
///
public class HttpFile
{
///
/// Initializes a new instance of the class.
///
[JsonConstructor]
public HttpFile()
{
}
///
/// Initializes a new instance of the class.
///
/// The stream to download.
/// The filename to use when downloading the stream.
/// The content type to use when downloading the stream.
/// The ETag to use when downloading the stream.
public HttpFile(Stream stream, string? filename = default, string? contentType = default, string? eTag = default)
{
Stream = stream;
Filename = filename;
ContentType = contentType;
ETag = eTag;
}
///
/// The file stream.
///
public Stream Stream { get; set; } = default!;
///
/// The filename.
///
public string? Filename { get; set; }
///
/// The content type.
///
public string? ContentType { get; set; }
///
/// The ETag.
///
public string? ETag { get; set; }
///
/// Gets the file bytes.
///
public byte[] GetBytes()
{
using var memoryStream = new MemoryStream();
if (Stream.CanSeek) Stream.Seek(0, SeekOrigin.Begin);
Stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
public StreamContent GetStreamContent()
{
if (Stream.CanSeek) Stream.Seek(0, SeekOrigin.Begin);
var content = new StreamContent(Stream);
if (!string.IsNullOrWhiteSpace(Filename))
{
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = Filename,
FileName = Filename,
FileNameStar = Filename
};
}
if (!string.IsNullOrWhiteSpace(ContentType)) content.Headers.ContentType = new MediaTypeHeaderValue(ContentType);
if (!string.IsNullOrWhiteSpace(ETag)) content.Headers.TryAddWithoutValidation("ETag", ETag);
return content;
}
}