【问题标题】:Convert byte[] to MultipartFile将 byte[] 转换为 MultipartFile
【发布时间】:2020-05-07 09:38:33
【问题描述】:

我想创建一个 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

【问题讨论】:

  • 你说的是spring课MultipartFile
  • 我看到了这个,但是我不明白如何将byte[]转换为MultipartFile,他有transferTo(File dest),但我没有File。
  • @Maurice ,是的,我使用 Springboot,我需要类型的对象 -> MultipartFile

标签: java spring


【解决方案1】:

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

【讨论】:

  • 您实例化这个类的一个实例并将字节数组传递给构造函数。还要确保 getName() 返回您的服务器期望的“部分”的名称,否则您将看到异常。
猜你喜欢
  • 2021-06-11
  • 2018-12-10
  • 2013-08-10
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 2020-06-08
相关资源
最近更新 更多