1

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
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
EduBw
  • 866
  • 5
  • 20
  • 40

1 Answers1

3

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);
        }
    }
Dipankar Baghel
  • 1,932
  • 2
  • 12
  • 24
  • 1
    You instantiate an instance of this class and pass the byte array into the constructor. Also ensure that getName() returns the name of the "part" your server is expecting or you will see an exception. – Steve May 19 '20 at 16:04