检查java中文件的类型(csv或excel文件(xlsx))



我需要上传一个文件。在上传之前,我需要知道文件是csv还是excel文件(xlsx)。如果是csv或excel文件,我将继续,否则退出。如何使用java中文件的路径来知道文件的类型。

您可以为此使用probeContentType(Path path)

探测文件的内容类型。

如果content-typetext/csv,则它是.csv文件。如果content-typeapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet,则它是.xlsx文件。

你应该试试这样的东西:

File file = new File("some path");
Path filePath = file.toPath();
String contentType = probeContentType(filePath);
if("text/csv".equals(contentType)) { 
  ...
}
  <?php
  $mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
    if(in_array($_FILES['file']['type'],$mimes)){
      // do something
    } else {
      die("Sorry, mime type not allowed");
    }
?>

最新更新