通过流的方式把文件存到数据库

保存方法

 @Override
    public String uploadFile(MultipartFile file, String fileId) {
        try {
            byte[] baseStr1 =file.getBytes();
//        // 获取文件后缀
            String fileName = file.getOriginalFilename();
            String fileExtension = "";
            int lastIndex = fileName.lastIndexOf('.');
            if (lastIndex > 0)
            {
                fileExtension = fileName.substring(lastIndex + 1);
            }
            ByteArrayInputStream inputStream = new ByteArrayInputStream(baseStr1);

            byte[] chunk = new byte[78000];
            int bytesRead;
            int chunkIndex = 0;
            String s = null;
            if (StringUtils.isBlank(fileId)){
                s = UUID.fastUUID().toString();
            }else{
                s = fileId;
            }

            while ((bytesRead = inputStream.read(chunk)) != -1) {
                FileUploadBlob fileUploadBlob=new FileUploadBlob();
                fileUploadBlob.setBlobData(chunk);
                fileUploadBlob.setChunkIndex(chunkIndex);
                fileUploadBlob.setFileId(s);
                fileUploadBlob.setType(fileExtension);
                fileUploadBlobMapper.insert(fileUploadBlob);
                chunkIndex++;

                // 如果当前块的大小不足70000字节,说明BLOB数据已经全部插入到数据库中
                if (bytesRead < 78000) {
                    break;
                }

                // 否则,读取下一个块
                chunk = new byte[78000];
            }

            inputStream.close();
            return s;
        }catch (IOException e){
            e.printStackTrace();
            log.error(e.getMessage());
            return null;
        }
    }



查询方法

@Override
    public String getFileByte(String fileId) {
        try {
            QueryWrapper qw =new QueryWrapper<>();
            qw.eq("file_id",fileId);
            qw.orderByAsc("chunk_index");
            List list = fileUploadBlobMapper.selectList(qw);
//            StringBuffer str = new StringBuffer();
            if (!CollectionUtils.isEmpty(list)){
                Future str = getBaseStr(list);

                String fileSuffix = list.get(0).getType();
                String prefix = "";
                switch (fileSuffix){
                    case "doc":
                        prefix = "data:application/msword;base64,";
                        break;
                    case "docx":
                        prefix = "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,";
                        break;
                    case "xls":
                        prefix = "data:application/vnd.ms-excel;base64,";
                        break;
                    case "xlsx":
                        prefix = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,";
                        break;
                    case "ppt":
                        prefix = "data:application/vnd.ms-powerpoint;base64,";
                        break;
                    case "pptx":
                        prefix = "data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,";
                        break;
                    case "pdf":
                        prefix = "data:application/pdf;base64,";
                        break;
                    case "jpg":
                        prefix = "data:image/jpeg;base64,";
                        break;
                    case "png":
                        prefix = "data:image/png;base64,";
                        break;
                    case "gif":
                        prefix = "data:image/gif;base64,";
                        break;
                    case "bmp":
                        prefix = "data:image/bmp;base64,";
                        break;
                    case "tif":
                        prefix = "data:image/tiff;base64,";
                        break;
                    case "txt":
                        prefix = "data:text/plain;base64,";
                        break;
                    case "svg":
                        prefix = "data:image/svg+xml;base64,";
                        break;
                    case "jpeg":
                        prefix = "data:image/jpeg;base64,";
                        break;
                }
                return prefix + str.get();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return null;
        }
    }

private static final int RANGE_UNIT = 1024 * 1024 * 4;
//多线程通过字节流获取base64
     public String getBaseStr(List list){
        StringBuffer str = new StringBuffer();
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            for (FileUploadBlob chunk : list) {
                byte[] chunkData = chunk.getBlobData();
                outputStream.write(chunkData);
                //防止内存溢出
                if (chunkData.length > RANGE_UNIT) {
                    byte[] blobData = outputStream.toByteArray();
                    String s = java.util.Base64.getEncoder().encodeToString(blobData);
                    str.append(s);
                    outputStream.flush();
                    outputStream.close();

                }
            }
            byte[] blobData = outputStream.toByteArray();
            String s = java.util.Base64.getEncoder().encodeToString(blobData);
            outputStream.flush();
            outputStream.close();
            str.append(s);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

        return str.toString();
    }

你可能感兴趣的:(通过流的方式把文件存到数据库)