我想创建一个File Excel,将此文件转换为MultipartFile.class,因为我已经测试过读取文件MultipartFile,因此创建了我的文件,但是我不知道将byte []转换为MultipartFile,因为我的函数读取了MultipartFile。

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.getSheetAt(0);
        XSSFRow row = sheet.createRow((short) 1);
        row.createCell(0).setCellValue("2019");
        row.createCell(1).setCellValue("11");
        row.createCell(2).setCellValue("1");
        row.createCell(3).setCellValue("2");

        byte[] fileContent = null;
        ByteArrayOutputStream bos = null;

        bos = new ByteArrayOutputStream();
        workbook.write(bos);
        workbook.close();
        fileContent = bos.toByteArray();
        bos.close();


        MultipartFile multipart = (MultipartFile) fileContent;


呃:

Cannot cast from byte[] to MultipartFile

最佳答案

MultipartFile是一个接口,因此请提供您自己的实现并包装您的字节数组。

使用以下课程-

public class BASE64DecodedMultipartFile implements MultipartFile {
        private final byte[] imgContent;

        public BASE64DecodedMultipartFile(byte[] imgContent) {
            this.imgContent = imgContent;
        }

        @Override
        public String getName() {
            // TODO - implementation depends on your requirements
            return null;
        }

        @Override
        public String getOriginalFilename() {
            // TODO - implementation depends on your requirements
            return null;
        }

        @Override
        public String getContentType() {
            // TODO - implementation depends on your requirements
            return null;
        }

        @Override
        public boolean isEmpty() {
            return imgContent == null || imgContent.length == 0;
        }

        @Override
        public long getSize() {
            return imgContent.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return imgContent;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(imgContent);
        }

        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            new FileOutputStream(dest).write(imgContent);
        }
    }

10-07 15:30