根据后缀名获取content-type

  • Post author:
  • Post category:其他


/**
 * 通过文件名判断并获取OSS服务文件上传时文件的contentType
 * @param fileName 文件名
 * @return 文件的contentType
 */
public String getContentType(String fileExtension){
    //文件的后缀名
    if("bmp".equalsIgnoreCase(fileExtension)) {
        return "image/bmp";
    }
    if("gif".equalsIgnoreCase(fileExtension)) {
        return "image/gif";
    }
    if("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension)  || "png".equalsIgnoreCase(fileExtension) ) {
        return "image/jpeg";
    }
    if("html".equalsIgnoreCase(fileExtension)) {
        return "text/html";
    }
    if("txt".equalsIgnoreCase(fileExtension)) {
        return "text/plain";
    }
    if("vsd".equalsIgnoreCase(fileExtension)) {
        return "application/vnd.visio";
    }
    if("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
        return "application/vnd.ms-powerpoint";
    }
    if("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
        return "application/msword";
    }
    if ("xls".equalsIgnoreCase(fileExtension) || "xlsx".equalsIgnoreCase(fileExtension)) {
        return "application/msexcel";
    }
    if ("csv".equalsIgnoreCase(fileExtension)) {
        return "application/csv";
    }
    if("xml".equalsIgnoreCase(fileExtension)) {
        return "text/xml";
    }
    if("mp4".equalsIgnoreCase(fileExtension)) {
        return "video/mp4";
    }
    if("avi".equalsIgnoreCase(fileExtension)) {
        return "video/x-msvideo";
    }
    if("mov".equalsIgnoreCase(fileExtension)) {
        return "video/quicktime";
    }
    if("mpeg".equalsIgnoreCase(fileExtension) || "mpg".equalsIgnoreCase(fileExtension)) {
        return "video/mpeg";
    }
    if("wm".equalsIgnoreCase(fileExtension)) {
        return "video/x-ms-wmv";
    }
    if("flv".equalsIgnoreCase(fileExtension)) {
        return "video/x-flv";
    }
    if("mkv".equalsIgnoreCase(fileExtension)) {
        return "video/x-matroska";
    }
    //默认返回类型
    return "video/x-msvideo";
}

或者

public enum ContentTypeEnum {

    BMP("image/bmp"),
    GIF("image/gif"),
    JPEG("image/jpeg"),
    JPG("image/jpeg"),
    PNG("image/png"),
    HTML("text/html"),
    TXT("text/plain"),
    XML("text/xml"),
    VSD("application/vnd.visio"),
    PPT("application/vnd.ms-powerpoint"),
    PPTX("application/vnd.ms-powerpoint"),
    DOC("application/msword"),
    DOCX("application/msword"),
    XLS("application/msexcel"),
    XLSX("application/msexcel"),
    CSV("application/csv"),;
    
    private String contenType;

    ContentTypeEnum(String contenType) {
        this.contenType = contenType;
    }

    public String getContenType() {
        return contenType;
    }
}



版权声明:本文为ownfire原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。