I need to upload files from a client to a server. But I found a problem, I can not filter the files. I need to discard files that do not have a suitable extension . If the file does not have the right extension then I will not load it to the server.
I tried to filter, but I don't have any idea how to write this. Can anyone help me with this part?
public enum FileExtension
{
Unknown = 0,
Doc = 1,
Rtf = 2,
Html = 3
}
public static class FileExtensionExtensions {
public static string GetExtension(this FileExtension ext) {
switch (ext) {
case FileExtension.Doc:
return ".doc";
case FileExtension.Html:
return ".html";
case FileExtension.Rtf:
return ".rtf";
default:
throw new ArgumentException();
}
}
public static FileExtension GetFileExtension(string ext) {
if (string.IsNullOrWhiteSpace(ext)) throw new ArgumentException("message", nameof(ext));
ext = ext.Trim('.').ToLower();
switch (ext) {
case ".doc":
return FileExtension.Doc;
case ".html":
return FileExtension.Html;
case ".rtf":
return FileExtension.Rtf;
default:
throw new ArgumentException();
}
}
}
[Route("api")][ApiController]
public class UploadDownloadController:
ControllerBase {
private IHostingEnvironment _hostingEnvironment;
public UploadDownloadController(IHostingEnvironment environment) {
_hostingEnvironment = environment;
}
[HttpPost][Route("upload")]
public async Task < IActionResult > Upload(IFormFile file) {
string fileExtension = Path.GetExtension(file.FileName).Trim('.');
if (file.Length > 0) {
string dir = Folder.GetAllPath(Path.Combine(Folder.GetAllPath, fileExtension));
string filePath = Path.Combine(dir, file.FileName);
using(var fileStream = new FileStream(filePath, FileMode.Create)) {
await file.CopyToAsync(fileStream);
}
}
return Ok();
}
[HttpGet][Route("download")]
public async Task < IActionResult > Download([FromQuery] string file) {
string fileExtension = Path.GetExtension(file).Trim('.');
string dir = Folder.GetAllPath(Path.Combine(Folder.GetAllPath, fileExtension));
string filePath = Path.Combine(dir, file);
if (!System.IO.File.Exists(filePath)) return NotFound();
var memory = new MemoryStream();
using(var stream = new FileStream(filePath, FileMode.Open)) {
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(filePath), file);
}
[HttpGet][Route("files")]
public IActionResult Files() {
var result = new List < string > ();
if (Directory.Exists(Folder.GetAllPath("txt"))) {
var files = Directory.GetFiles(Folder.GetAllPath("txt")).Select(fn = >Path.GetFileName(fn));
result.AddRange(files);
}
return Ok(result);
}
private string GetContentType(string path) {
var provider = new FileExtensionContentTypeProvider();
string contentType;
if (!provider.TryGetContentType(path, out contentType)) {
contentType = "application/octet-stream";
}
return contentType;
}
}
}