Skip to content

Instantly share code, notes, and snippets.

@kasuken
Created January 25, 2018 07:24
Show Gist options
  • Save kasuken/7c238db6005a730325dedd8eaf8f0a29 to your computer and use it in GitHub Desktop.
Save kasuken/7c238db6005a730325dedd8eaf8f0a29 to your computer and use it in GitHub Desktop.
Download and Upload files via Web API
[Route("api/[controller]")]
public class FilesController : ControllerBase
{
[HttpGet]
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename not present");
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "download", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, MimeTypeMap.GetMimeType(Path.GetExtension(path)), Path.GetFileName(path));
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile uploadedFile)
{
if (uploadedFile == null || uploadedFile.Length == 0)
return Content("file not selected");
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", uploadedFile.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await uploadedFile.CopyToAsync(stream);
}
return Ok();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment