@manhnguyenv

Welcome to my blog!

Upload Files in ASP.NET Core Web API

November 11, 2019 23:07

Upload Files in ASP.NET Core Web API (edit)

https://ilclubdellesei.blog/2018/02/14/how-to-upload-images-to-an-asp-net-core-rest-service-with-xamarin-forms/

https://github.com/phenixita/IC6.Xamarin.PictureUpload

https://dotnetthoughts.net/attribute-routing-in-aspnet-core/

Controller in ASP.NET Core Web API

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;

namespace AspNetCoreWebApi.Controllers
{
/// <summary>
///
/// </summary>
[ApiController]
public class ValuesController : ControllerBase
{
private readonly ILogger<ValuesController> _logger;

public ValuesController(ILogger<ValuesController> logger)
{
_logger = logger;

_logger.LogInformation("ValuesController called.");
}

[HttpGet]
[Route("api/Values/")]
public IActionResult Get()
{
return Ok("Success");
}

/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost]
[Route("/Values/PostFile")]
public IActionResult PostFile(IFormFile file)
{
_logger.LogInformation("ValuesController.PostFile method called.");

var inputStream = file.OpenReadStream();

string fileName = file.FileName;

string filePath = Utils.GenerateFilePathInDesktop(fileName);

if (!string.IsNullOrWhiteSpace(filePath))
{
using (FileStream outputFileStream = new FileStream(filePath, FileMode.Create))
{
inputStream.CopyTo(outputFileStream);

return Ok("OK");
}
}

return Ok("Error.");
}

/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost]
[Route("/Values/UploadFile")]
public async Task<IActionResult> UploadFile(IFormFile file)
{
byte[] byteArray;

using (var ms = new MemoryStream())
{
await file.CopyToAsync(ms);

byteArray = ms.ToArray();

string fileName = file.FileName;

string filePath = Utils.GenerateFilePathInDesktop(fileName);

if (!string.IsNullOrWhiteSpace(filePath))
{
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(byteArray, 0, byteArray.Length);

return Ok("OK");
}
}

return Ok("Error.");
}
}
}

public static class Utils
{
public static string GenerateFilePathInDesktop(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName)) return string.Empty;

if (!fileName.Contains(".")) return string.Empty;

var arr = fileName.Split(new char[] { '.' });

var fileNameWithoutExt = arr[0];

var fileExtension = arr[1];

string filePath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) +
@"\" + string.Format("{0}_{1}.{2}", fileNameWithoutExt, System.DateTime.Now.ToString("yyyyMMddhhmmss"), fileExtension);

return filePath;
}
}
}

Test

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace AspNetCoreWebApi.Test
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(System.DateTime.Now.ToString("yyyyMMddhhmmss"));

UploadFiles();
}

private static void UploadFiles()
{
string endpoint = "https://localhost:44306/Values/PostFile/";

string filePath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + "DATA.xlsx";

string fileName = System.IO.Path.GetFileName(filePath);

bool isSuccessUpload = false;

using (FileStream stream = File.Open(filePath, FileMode.Open))
{
IApiService apiService = new ApiService();

Task<bool> task = apiService.UploadImageAsync(endpoint, stream, fileName);

task.Wait();

isSuccessUpload = task.Result;
}

Console.WriteLine(isSuccessUpload ? "Done!" : "Failed.");
}
}

public interface IApiService
{
Task<bool> UploadImageAsync(string uri, Stream image, string fileName);
}

public class ApiService : IApiService
{
public async Task<bool> UploadImageAsync(string uri, Stream image, string fileName)
{
HttpContent fileStreamContent = new StreamContent(image);
fileStreamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName };
fileStreamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent);
var response = await client.PostAsync(uri, formData);
return response.IsSuccessStatusCode;
}
}
}
}

Categories

Recent posts