在java中检查文件的types(csv或excel文件(xlsx))

我需要上传一个文件。 在我上传之前,我需要知道该文件是csv还是excel文件(xlsx)。 如果是csv或excel文件,我会继续退出。 我怎么能通过使用它的path知道在java文件的types。

您可以使用probeContentType(Path path)

探测文件的内容types。

如果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)) { ... } 
 $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"); }