Skip to content

Added the possibility to specify the content type of the uploaded file #8474

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ public sealed class FileReference
{
private readonly Func<Stream> _openRead;

/// <inheritdoc cref="FileReference(Stream,string,string)"/>
public FileReference(Stream stream, string fileName)
: this(stream, fileName, null)
{
}

/// <summary>
/// Creates a new instance of <see cref="FileReference" />
/// </summary>
Expand All @@ -19,13 +25,16 @@ public sealed class FileReference
/// <param name="fileName">
/// The file name.
/// </param>
/// <param name="contentType">
/// The file content type.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="fileName"/> is <c>null</c>, empty or white space.
/// </exception>
public FileReference(Stream stream, string fileName)
public FileReference(Stream stream, string fileName, string? contentType)
{
ArgumentNullException.ThrowIfNull(stream);

Expand All @@ -38,6 +47,13 @@ public FileReference(Stream stream, string fileName)

_openRead = () => stream;
FileName = fileName;
ContentType = contentType;
}

/// <inheritdoc cref="FileReference(Func{Stream},string,string)"/>
public FileReference(Func<Stream> openRead, string fileName)
: this(openRead, fileName, null)
{
}

/// <summary>
Expand All @@ -49,13 +65,16 @@ public FileReference(Stream stream, string fileName)
/// <param name="fileName">
/// The file name.
/// </param>
/// <param name="contentType">
/// The file content type.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="fileName"/> is <c>null</c>, empty or white space.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="openRead"/> is <c>null</c>.
/// </exception>
public FileReference(Func<Stream> openRead, string fileName)
public FileReference(Func<Stream> openRead, string fileName, string? contentType)
{
if (string.IsNullOrWhiteSpace(fileName))
{
Expand All @@ -66,13 +85,19 @@ public FileReference(Func<Stream> openRead, string fileName)

_openRead = openRead ?? throw new ArgumentNullException(nameof(openRead));
FileName = fileName;
ContentType = contentType;
}

/// <summary>
/// The file name eg. <c>foo.txt</c>.
/// The file name e.g. <c>"foo.txt"</c>.
/// </summary>
public string FileName { get; }

/// <summary>
/// The content type of the file e.g. <c>"application/pdf"</c>.
/// </summary>
public string? ContentType { get; }

/// <summary>
/// Opens the file stream.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,13 @@ private static HttpContent CreateMultipartContent(

foreach (var fileInfo in fileInfos)
{
var file = new StreamContent(fileInfo.File.OpenRead());
form.Add(file, fileInfo.Name, fileInfo.File.FileName);
var fileContent = new StreamContent(fileInfo.File.OpenRead());
if (!string.IsNullOrEmpty(fileInfo.File.ContentType))
{
fileContent.Headers.ContentType = new MediaTypeHeaderValue(fileInfo.File.ContentType);
}

form.Add(fileContent, fileInfo.Name, fileInfo.File.FileName);
}

return form;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Net;
using System.Text;
using System.Text.Json;
using HotChocolate.AspNetCore.Tests.Utilities;
using HotChocolate.Language;
Expand Down Expand Up @@ -881,29 +882,39 @@ public async Task Get_Subscription_Over_SSE_With_Errors()
await snapshot.MatchMarkdownAsync(cts.Token);
}

[Fact]
public async Task Post_GraphQL_FileUpload()
[Theory]
[InlineData((string?)null)]
[InlineData("application/pdf")]
public async Task Post_GraphQL_FileUpload(string? contentType)
{
// arrange
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5000));
using var testServer = CreateStarWarsServer();
var httpClient = testServer.CreateClient();
var server = CreateStarWarsServer(
configureServices: s => s
.AddGraphQLServer("test")
.AddType<UploadType>()
.AddQueryType<UploadTestQuery>());
var httpClient = server.CreateClient();
var client = new DefaultGraphQLHttpClient(httpClient);

var stream = new MemoryStream("abc"u8.ToArray());

var operation = new OperationRequest(
"""
query ($upload: Upload!) {
singleUpload(file: $upload)
singleInfoUpload(file: $upload) {
name
content
contentType
}
}
""",
variables: new Dictionary<string, object?>
{
["upload"] = new FileReference(() => stream, "test.txt")
["upload"] = new FileReference(() => stream, "test.txt", contentType)
});

var requestUri = new Uri(CreateUrl("/upload"));
var requestUri = new Uri(CreateUrl("/test"));

var request = new GraphQLHttpRequest(operation, requestUri)
{
Expand All @@ -917,10 +928,14 @@ public async Task Post_GraphQL_FileUpload()
// assert
using var body = await response.ReadAsResultAsync(cts.Token);
body.MatchInlineSnapshot(
"""
$$$"""
{
"data": {
"singleUpload": "abc"
"singleInfoUpload": {
"name": "test.txt",
"content": "abc",
"contentType": "{{{contentType}}}"
}
}
}
""");
Expand Down Expand Up @@ -1006,4 +1021,26 @@ public async IAsyncEnumerable<string> CreateStream()
public string OnError([EventMessage] string message)
=> message;
}

public class UploadTestQuery
{
public async Task<FileInfoOutput> SingleInfoUpload(IFile file)
{
await using var stream = file.OpenReadStream();
using var sr = new StreamReader(stream, Encoding.UTF8);
return new FileInfoOutput
{
Content = await sr.ReadToEndAsync(),
ContentType = file.ContentType ?? string.Empty,
Name = file.Name
};
}

public class FileInfoOutput
{
public string? Content { get; init; }
public string? ContentType { get; init; }
public string? Name { get; init; }
}
}
}
19 changes: 17 additions & 2 deletions src/StrawberryShake/Client/src/Core/Upload.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@ namespace StrawberryShake;
/// </summary>
public readonly struct Upload
{
/// <inheritdoc cref="Upload(Stream, string, string?)"/>
public Upload(Stream content, string fileName)
: this(content, fileName, null)
{
}

/// <summary>
/// Creates a new instance of Upload
/// Creates a new instance of the Upload-scalar.
/// </summary>
public Upload(Stream content, string fileName)
public Upload(Stream content, string fileName, string? contentType)
{
Content = content;
FileName = fileName;
ContentType = contentType;
}

/// <summary>
Expand All @@ -23,4 +30,12 @@ public Upload(Stream content, string fileName)
/// The name of the file
/// </summary>
public string FileName { get; }

/// <summary>
/// The optional MIME type of the file.
/// </summary>
/// <remarks>
/// If specified, this value is applied as the HTTP Content-Type header.
/// </remarks>
public string? ContentType { get; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ private static void MapVariables(List<object?> variables)
{
case Dictionary<string, object> result:
result[currentPath] =
new FileReference(upload.Value.Content, upload.Value.FileName);
new FileReference(upload.Value.Content, upload.Value.FileName, upload.Value.ContentType);
break;

case List<object> array:
Expand All @@ -258,7 +258,7 @@ private static void MapVariables(List<object?> variables)
}

array[arrayIndex] =
new FileReference(upload.Value.Content, upload.Value.FileName);
new FileReference(upload.Value.Content, upload.Value.FileName, upload.Value.ContentType);

break;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ await interceptor
default:
if (fileValue is Upload upload)
{
return new StreamFile(upload.FileName, () => upload.Content);
return new StreamFile(upload.FileName, () => upload.Content, null, upload.ContentType);
}

return variables;
Expand Down
Loading