EduBw
EduBw

Reputation: 942

Convert byte[] to MultipartFile

I want create a File Excel, convert this file to MultipartFile.class because I have test that read files MultipartFile, I created my file, but I don't know transform byte[] to MultipartFile because my function read 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;

err:

Cannot cast from byte[] to MultipartFile

Upvotes: 1

Views: 17630

Answers (1)

Dipankar Baghel
Dipankar Baghel

Reputation: 2059

MultipartFile is an interface so provide your own implementation and wrap your byte array.

Use below class -

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);
        }
    }

Upvotes: 3

Related Questions