MultipleFile转File、File转Byte

MultipleFile转File、File转Byte 工具类

/**
     * file2byte
     * @param file
     * @return
     */
    public static byte[] convertFileToByteArray(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] byteArray = new byte[(int) file.length()];
            fis.read(byteArray);
            fis.close();
            return byteArray;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * MultipartFile2File
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static File convert2File(MultipartFile multipartFile) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
        File file = File.createTempFile(multipartFile.getOriginalFilename(), ".tmp");
        FileOutputStream outputStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        file.deleteOnExit();
        File tempFile = new File("temp_image/" + multipartFile.getOriginalFilename());
        boolean delete = tempFile.delete();
        return file;
    }

你可能感兴趣的:(java,前端,开发语言)