-
Couldn't load subscription status.
- Fork 11
File upload download
Stanislav Molchanovskiy edited this page Nov 15, 2021
·
1 revision
Clients and controllers are able to upload and download files. Here's how you can implement this on the client and on the server:
On the controller side, you do not need to perform any special actions, work with files as in the original ASP.NET Core:
[HttpFacade, Path("api/[controller]")]
public interface IFileController
{
[GetMethod("files/{id}")] Task<IActionResult> GetFileAsync([RouteParam] long id);
[PostMethod("files")] Task PostFileAsync(byte[] fileBytes);
}
public class FileController : ControllerBase, IFileController
{
public async Task<IActionResult> GetTextFileAsync(long id) =>
PhysicalFile(physicalPath: "/TextFile.txt", contentType: "text/plain");
public Task PostTextFileAsync(byte[] fileBytes) =>
...;
}Since one method from the IFileController returns the IActionResult, it is necessary to override it using the IHttpResponse as the return value:
public interface IFileClient : IFileController
{
[Override] new Task<IHttpResponse> GetFileAsync([RouteParam] long id);
}After creating an interface for a client with an overridden method, you can create a client for downloading and uploading files:
IFileClient client = NClientGallery.Clients.GetRest()
.For<IFileClient>(host: "http://localhost:8080")
.Build();
var httpResponseWithFile = await client.GetFileAsync(id: 1);
var fileBytes = httpResponseWithFile.Content.Bytes;
var fileBytesForSave = ...;
await client.PostFileAsync(fileBytesForSave);To work with streams, return a HttpResponseMessage instead of a IHttpResponse.