基于base64的文件上传

package com.cdls.carp.common.util;

import com.cdls.carp.common.constant.Constant;
import com.cdls.carp.common.exception.BaseException;
import com.cdls.carp.common.result.ResultEnum;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import java.io.*;

/**
 * 将base64编码字符串转换为图片
 * @author xrj
 * @date 2020/4/2
 */
@Component
public class Base64ToImage {

    /**
     * 获取文件名
     * 生成机制:当前的时间戳 + 0~100的随机数
     * @return 文件名
     */
    private static String getFileName() {
        long time = System.currentTimeMillis();
        long index = time + Math.round(100);
        return index + ".jpg";
    }

    /**
     * 去除data:image/jpeg;base64,字符串
     * @param base64str base64字符串
     * @return base64字符串
     */
    private static String formatBase64(String base64str) {
        int num = base64str.indexOf(",");
        return base64str.substring(num + 1);
    }

    /**
     * 上传base64图片
     * @param base64str base64字符串
     * @param localPath 本地路径
     * @param netPath 网络路径
     * @throws FileNotFoundException FileNotFoundException
     */
    public static String uploadImg(String base64str, String localPath, String netPath) throws FileNotFoundException {
        if(base64str.contains(";base64,")) {
            base64str = formatBase64(base64str);
        }

        String fileName = getFileName();
        String timePath = UploadUtil.getTimePath();
        String path = localPath + "/image" + "/" +timePath+fileName;
        checkFileExist(path);
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = new FileOutputStream(path);
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(base64str);
            // 处理数据
            return dealWithData(b, out, timePath, fileName, netPath);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 处理数据
     * @param b base64字节数组
     * @param out 输出流
     * @param timePath 时间路径
     * @param fileName 文件名
     * @param netPath 网络路径
     * @return 文件的网络路径
     * @throws IOException IOException
     */
    private static String dealWithData(byte[] b, OutputStream out, String timePath, String fileName, String netPath) throws IOException {
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        out.write(b);
        out.flush();
        return netPath + "/" + timePath + fileName;
    }

    /**
     * 判断路径是否存在
     * @param path 路径
     */
    private static void checkFileExist(String path) {
        File distFile = new File(path);
        if (!distFile.getParentFile().exists()) {
            boolean b = distFile.getParentFile().mkdirs();
            if(!b) {
                throw new BaseException(Constant.BUSINESS, ResultEnum.PARAMETER_EXCEPTION);
            }
        }
    }


}
package com.cdls.carp.business.controller;

import com.cdls.carp.business.annotation.Log;
import com.cdls.carp.business.enumerate.MethodTypeEnum;
import com.cdls.carp.common.constant.Constant;
import com.cdls.carp.common.exception.BaseException;
import com.cdls.carp.common.result.CarpResult;
import com.cdls.carp.common.result.ResultEnum;
import com.cdls.carp.common.util.Base64ToImage;
import com.cdls.carp.common.util.DownLoadUtil;
import com.cdls.carp.common.util.UploadUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yjw
 */
@Api(tags = "文件相关接口")
@RestController
@RequestMapping("/a/q/upload")
@Slf4j
public class FileController {

    @Value("${upload.localPath}")
    private String localPath;

    @Value("${upload.netPath}")
    private String netPath;

    @PostMapping(value = "/uploadImgs")
    @ApiOperation(value = "上传base64多文件")
    @ApiImplicitParam(name = "imgList", value = "base64文件数组", paramType = "body", required = true, dataType = "String")
    @Log(module = Constant.BUSINESS, content = "多文件上传", actionUrl = "/a/q/upload/load/uploadImgs", type = MethodTypeEnum.UPDATE)
    public CarpResult<List<String>> uploadImgs(@RequestBody List<String> imgList) throws FileNotFoundException {
        if(imgList.size() < 1) {
            throw new BaseException(Constant.BUSINESS, ResultEnum.PARAMETER_EXCEPTION);
        }
        List<String> list = new ArrayList<>();
        String netPath;
        for (String img : imgList) {
            netPath = Base64ToImage.uploadImg(img, localPath, this.netPath);
            list.add(netPath);
        }
        return new CarpResult<>(ResultEnum.FILE_UPLOAD_SUCCESS, list);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值