Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中如何从文件中获取幻数_Java_File Extension_Magic Numbers - Fatal编程技术网

java中如何从文件中获取幻数

java中如何从文件中获取幻数,java,file-extension,magic-numbers,Java,File Extension,Magic Numbers,我有“上传文件”按钮中的文件,我想用magic number打印扩展名文件 我的代码: UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue(); byte[] fileByteArray = IOUtils.toByteArray(file.getInputStream()); 注意:Mime类型和内容文件(来自文件和文件名)与幻数不同(幻数来自inputStream的第一个字节) 我该怎么做?我知道这是一个老问题,请把

我有“上传文件”按钮中的文件,我想用magic number打印扩展名文件

我的代码:

UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
byte[] fileByteArray = IOUtils.toByteArray(file.getInputStream());
注意:Mime类型和内容文件(来自文件和文件名)与幻数不同(幻数来自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;
    }
}
文件幻数的参考:


我把我的解决方案放在没有java servlet相关代码的情况下,以防人们想要一个替代方案:

公共枚举MagicBytes{
PNG(0x89,0x50),//定义与前面的答案相同
JPG(0xFF,0xD8),
PDF(0x25,0x50);
私人最终整数[]魔法字节;
专用MagicBytes(整数…字节){
magicBytes=字节;
}
//检查字节是否与特定的魔法字节序列匹配
公共布尔值为(字节[]字节){
if(bytes.length!=magicBytes.length)
抛出新的RuntimeException(“我需要第一个”+magicBytes.length
+“输入流的字节。”);

对于(int i=0;i您能否澄清“使用magic number打印扩展文件”的含义?我想控制文件类型,但不想使用mime type或getContentType()函数,我只想使用magic number(来自输入流的第一个字节)很多文件类型的可能副本没有一个神奇的数字。呵呵,是吗?还有一些简单的类型,如JPEG、PNG、GIF、PDF、XLS?你有一个goog链接,例如代码吗?非常感谢