上传图片并经过Base64加密保存到数据库(内含MultipartFile转File)

1、

    @ResponseBody
    @RequestMapping("/upload")
    public AjaxResult upload(ShopCode shopCode, MultipartFile file) throws IOException {

        if (file.equals("") || file.getSize() <= 0) {
            return AjaxResult.error("图片不能为空");
        }

        //MultipartFile转File
        File file2 = null;
        file2 = File.createTempFile(UUID.randomUUID().toString(), "tmp");//创建临时文件
        file.transferTo(file2);//MultipartFile写到File文件中

        shopCode.setPic(EnPicUtil.enPic(file2));
        file2.deleteOnExit();//JVM虚拟机退出时删除临时文件,也可以调用file2.delete()立即删除
        
        shopCodeService.add(shopCode);
        。。。。。。
    }

2、File经过base64加密

public class EnPicUtil {

    public static String enPic(File file) throws IOException {

        public static String enPic(File file) throws IOException {

        FileInputStream fis = new FileInputStream(file);
        byte[] arr = new byte[5242880];
        int read = fis.read(arr);
        byte[] arrByte = new byte[read];
        System.arraycopy(arr, 0, arrByte, 0, read);
        String s = Base64.getEncoder().encodeToString(arrByte);
        return s;
    }
发布了39 篇原创文章 · 获赞 6 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_40155654/article/details/101604246