1. 程式人生 > 實用技巧 >10行程式碼判斷上傳檔案的格式

10行程式碼判斷上傳檔案的格式

1.在每一個專案中,上傳檔案都是必不可少的功能。都需要限制上傳的檔案格式,那麼如何精準的判斷檔案格式呢,通過檔名字尾來判斷檔案格式感覺也不是太靠譜,這裡使用了apache-tika框架,

步驟1:先引入依賴

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>1.9</version>
</dependency>  
 步驟2:引入工具類
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;

import java.io.IOException;
import java.io.InputStream;

/**
* @Description 檔案工具類
* MimeType 檔案型別
* application/msword word(.doc)
* application/vnd.ms-powerpoint powerpoint(.ppt)
* application/vnd.ms-excel excel(.xls)
* application/vnd.openxmlformats-officedocument.wordprocessingml.document word(.docx)
* application/vnd.openxmlformats-officedocument.presentationml.presentation powerpoint(.pptx)
* application/vnd.openxmlformats-officedocument.spreadsheetml.sheet excel(.xlsx)
* application/x-rar-compressed rar
* application/zip zip
* application/pdf pdf
* video/* 視訊檔案
* image/* 圖片檔案
* text/plain 純文字
* text/css css檔案
* text/html html檔案
* text/x-java-source java原始碼
* text/x-csrc c原始碼
* text/x-c++src c++原始碼
* @Date 2020/7/17 14:21
* @Author dengxiaoyu
*/
@Slf4j
public class FileUtil {
public static String getMimeType(InputStream inputStream) {
Tika tika = new Tika();
String detect = "";
try {
detect = tika.detect(inputStream);
} catch (IOException e) {
log.error("獲取檔案型別異常", e);
}
return detect;
}
}

步驟3:呼叫MultipartFile物件的getInputStream()方法獲取inputstream,再呼叫FileUtil的getMimeType方法。