java - 如何从java中的文件中获取魔数(Magic Number)

标签 java file-extension magic-numbers

我有来自 UploadedFile 按钮的文件,我想使用魔数(Magic Number)打印扩展文件,

我的代码:

UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
byte[] fileByteArray = IOUtils.toByteArray(file.getInputStream());

注意:Mime 类型和内容文件(来自文件和来自文件名)与魔数(Magic Number)不同(魔数(Magic Number)来自 inputStream 的第一个字节)

我该怎么做?

最佳答案

我知道这是一个老问题,只需将我的答案放在这里,希望有人在搜索相同的解决方案时发现它很有用。

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

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import javax.servlet.annotation.MultipartConfig;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@MultipartConfig(
    fileSizeThreshold = 0,
    maxFileSize = 1024 * 1024 * 50,       // 50MB
    maxRequestSize = 1024 * 1024 * 100)   // 100MB
public class FileUpload extends HttpServlet {    

    private static final Logger logger = LogManager.getLogger(FileUpload.class);
    private byte[] data = new byte[4];

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        try {
            fileSignature(request
              .getPart("image_file")
              .getInputStream());
        } catch (IOException | NullPointerException ex) {
            logger.error(ex);
        }

        String fileType = getFileType(data);

        // return the recognized type 
        response.getWriter().write(fileType);
    }

    /**
     * Get the first 4 byte of a file file signature. 
     * 
     * @param part File from part.
     */
     private void fileSignature(InputStream is)
             throws IOException, NullPointerException {
         is.read(data, 0, 4);
     }

     /**
      * Get the file type based on the file signature.
      * Here restricted to only recognized file type jpeg, jpg, png and
      * pdf where the signature of jpg and jpeg files are the same.
      *
      * @param fileData Byte array of the file.
      * @return String of the file type.
      */
     private String getFileType(byte[] fileData) {
         String type = "undefined";
         if(Byte.toUnsignedInt(fileData[0]) == 0x89 && Byte.toUnsignedInt(fileData[1]) == 0x50)
             type = "png";
         else if(Byte.toUnsignedInt(fileData[0]) == 0xFF && Byte.toUnsignedInt(fileData[1]) == 0xD8)
             type = "jpg";
         else if(Byte.toUnsignedInt(fileData[0]) == 0x25 && Byte.toUnsignedInt(fileData[1]) == 0x50)
             type = "pdf";

        return type;
    }
}

文件魔数(Magic Number)引用:
  • filesignatures.net
  • Wikipedia List of file signatures
  • mimesniff
  • GCK'S FILE SIGNATURES TABLE
  • 关于java - 如何从java中的文件中获取魔数(Magic Number),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206540/

    相关文章:

    java - 我的 spring boot 应用程序的新版本无法连接到 mysql

    java - Spring批量写入固定格式文件

    vba - 如果文件扩展名为 .xls,则 MsgBox

    c# - 带有扩展的 ASP.NET Webforms 路由

    java - 为什么我们在 .class 文件的开头需要一个魔数(Magic Number)?

    java - 在 Java printf 格式说明符中丢失魔数(Magic Number)以生成列

    java - Java 中的 OurCompanyRuntimeException 类型有什么意义?

    git - 如何根据文件扩展名过滤 git diff?

    r - 加载工作区时出现 "bad magic number"错误的原因以及如何避免?

    java - IProgressMonitor 如何暂停?