我需要将文件从客户端上传到服务器。但是我发现了一个问题,我无法过滤文件。我需要丢弃没有合适扩展名的文件。如果文件没有正确的扩展名,那么我将不会将其加载到服务器。
我尝试过滤,但是我不知道该如何写。有人可以帮我这部分吗?
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;
}
}
}
答案 0 :(得分:0)
您的第一个问题是,您显示的代码是服务器端代码。这意味着您只能在文件(IFormFile)上载后检测文件类型。我假设您要在文件上传之前停止文件选择和文件上传。您将必须在客户端使用JavaScript或Angular等客户端框架进行此操作。
指针:在HTML DOM中定义文件输入时,您可以指定允许的扩展名。例如。 .txt,.csv您也可以将其扩展为mime类型。例如。图片/ jpg,图片/ gif。请注意,这并非万无一失,只能描述为尽力而为。仍然需要客户端验证。
<input type="file" accept=".txt, .csv" />
<input type="file" accept="image/jpg, image/gif">
<input type="file" accept=".txt, .csv, image/jpg, image/gif">