Created
January 25, 2018 07:24
-
-
Save kasuken/7c238db6005a730325dedd8eaf8f0a29 to your computer and use it in GitHub Desktop.
Download and Upload files via Web API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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