文件上传-base64转码

一、背景

1、当前对接政府平台,使用文件流MultipartFile格式传输文件不支持,因此改用base64将文件转化为base64字符形式,通过body传参,然后后台再通过base64将字符串转化为文件File。我们的文件系统使用的是fastdfs
2、代码

    /**
     * 上传并返回文件路径和文件名
     * @param file 文件
     * @return 文件路径
     * @throws IOException 异常
     */
    @ApiOperation(value = "上传并返回文件路径和文件名", notes = "上传并返回文件路径和文件名")
    @PostMapping(value = "/upload")
    ResponseInfo<Map<String, String>> upload(@RequestBody String file) throws IOException;

3、impl

    /**
     * 图片后缀集合
     */
    private static final Set<String> IMAGE_PREFIX_SET = Set.of("JPG", "JPEG", "PNG", "GIF", "BMP", "WBMP");

    /**
     * 文件服务器 客户端
     */
    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 文件名称
     */
    private static final String META_DATA_NAME_FILE_NAME = "FILE_NAME";

   
    @Override
    public Map<String, String> uploadAndInfoZheLiBan(String file) {
        Map<String, String> result = new HashMap<>(10);
        MultipartFile multipartFile = Base64DecodedMultipartFile.base64ToMultipart(JSONObject.parseObject(file).get("file").toString());
        String fileName = multipartFile.getOriginalFilename();
        //上传文件
        String path = upload(multipartFile);
        result.put("uri", path);
        result.put("name", fileName);
        return result;
    }
    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    private String upload(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String filePrefix = FilenameUtils.getExtension(fileName);
            StorePath storePath;
            if (IMAGE_PREFIX_SET.contains(filePrefix.toUpperCase())) {
                // 图片上传并且生成缩略图
                storePath = this.storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), filePrefix, Collections.singleton(new MetaData(META_DATA_NAME_FILE_NAME, fileName)));
            } else {
                // 普通文件上传
                storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), filePrefix, Collections.singleton(new MetaData(META_DATA_NAME_FILE_NAME, fileName)));
            }
            return storePath.getFullPath();
        } catch (IOException e) {
            log.error("batch upload file fail!", e);
        }
        return null;
    }

4、工具类

package com.ehe.setting.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Title:Base64DecodedMultipartFile
 * @Package:com.xpf.common.utils
 * @Author: xiapf
 * @Date:2019/12/18
 * @Descrption:
 */
public class Base64DecodedMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;
    /**
     * base64转MultipartFile
     * @param base64
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");
            byte[] b = java.util.Base64.getDecoder().decode(baseStrs[1]);
            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new Base64DecodedMultipartFile(b, baseStrs[0]);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Base64DecodedMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        // implementation depends on your requirements
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        //  implementation depends on your requirements
        return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        //  implementation depends on your requirements
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值