file和multipartfile相互转化及其poi提取图片

一,poi导入excel时提取图片

上传的excel

FileInputStream fs = (FileInputStream) file1.getInputStream();
            HSSFWorkbook workbook = null;
            if (".xls".equals(suffix)) {
                workbook = new HSSFWorkbook(fs);
            } else if (".xlsx".equals(suffix)) {
                workbook = (HSSFWorkbook) WorkbookFactory.create(fs);
            }
            ...
		//基本信息
        HSSFSheet sheet_jbxx = (HSSFSheet) workbook.getSheetAt(3);
        import_jbxx(sheet_jbxx,fileName, uuid,request);
			//获取头像
            List<HSSFShape> list = sheet_jbxx.getDrawingPatriarch().getChildren();
            SAttachmentFile attachmentFile = null;
            for (HSSFShape shape : list) {
                if (shape instanceof HSSFPicture) {
                    HSSFPicture picture = (HSSFPicture) shape;
                    HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
                    HSSFPictureData pdata = picture.getPictureData();
                    //获取第几行
                    HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
                    //获取行编号
                    int row = anchor.getRow2();
                    //获取列编号
                    int col = anchor.getCol2();
                    if(row!=1&&row==6&&col==4){
                        //文件字节数组
                        byte[] data = pdata.getData();
                        InputStream inputStream = new ByteArrayInputStream(data);
                        MultipartFile file = new MockMultipartFile("test.jpg","test.jpg",ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
                        String path="rygl/picture";
                        attachmentFile = fileManagerService.uploadFile(file,path);
                    }else if(row!=1&&(row!=6||col!=4)){
                        isshow=true;
                        jgMsg.append("文件名:"+fileName+",提示:照片读取失败,请在指定单元格内放置照片!;\r\n");
                    }

                }
            }
            if(attachmentFile!=null){
                a01.setZdyxa0106(attachmentFile.getFid());
            }

其中有一个byte数组转为MultipartFile的过程

二,byte数组和MultipartFile户转

MultipartFile转化为byte数组
byte[] imgBytes = multipartFile.getBytes();

byte数组转化为MultipartFile

转换中我们会使用MockMultipartFile这个类,所有要引用相应包。

                <dependency>
                   <groupId>org.springframework</groupId>
                   <artifactId>spring-test</artifactId>
                   <version>RELEASE</version>
                </dependency>
byte[] testFile = new byte[1024];
InputStream inputStream = new ByteArrayInputStream(testFile);
MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);

三,file转MultipartFile

引入以下依赖

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
public class FileUtil {
    public MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }
    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}

注意:导入的是org.apache.commons下的包

四,解压zip包

private void unzipAndImportExcels(MultipartFile file,HttpServletRequest request) throws IOException, InvalidFormatException, ParseException {
        //存放解压后的文件目录
        String destDirPath="D:\\工作\\北软工具和工作文件\\冬奥人员信息导入数据材料\\test\\";
        File tempDir=new File(destDirPath);
        //初始化临时目录
        FileUtils.cleanDirectory(tempDir);
        File file1 = new File(destDirPath+file.getOriginalFilename());

        FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
        ZipFile zipFile=new ZipFile(file1, Charset.forName("GBK"));
        Enumeration<?> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            // 如果是文件夹,就创建个文件夹
            if (entry.isDirectory()) {
                String dirPath = destDirPath + File.separator + entry.getName();
                File dir = new File(dirPath);
                dir.mkdirs();
            }else{
                // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                File targetFile = new File(destDirPath + File.separator + entry.getName());
                // 保证这个文件的父文件夹必须要存在
                if (!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                targetFile.createNewFile();
                // 将压缩文件内容写入到这个文件中
                InputStream is = zipFile.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(targetFile);
                int len;
                byte[] buf = new byte[1024];
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                // 关流顺序,先打开的后关闭
                fos.close();
                is.close();

            }
        }
        zipFile.close();
        //删除压缩包
        FileUtils.forceDelete(file1);
}
posted @ 2021-01-27 18:33  你樊不樊  阅读(492)  评论(0编辑  收藏  举报