快捷搜索: 王者荣耀 脱发

Java实现本地上传图片以及读取

1.配置application文件

pro.image.path=D:/test/
pro.categoryImage.path=D:/category/

2.控制层

@Value("${pro.image.path}")
    private String proImagePath;


 @PostMapping("/system-port/productPicture")
    @ResponseBody
    public void updateProductPicture() {
          
   
        Map result = new HashMap<>();
        var req = readJson();
        var imageStr = req.get("fileData").toString();
        var fileType = req.get("fileType").toString();
        var fileName = req.get("fileName").toString();

        var fileMap = Map.of(
                "fileData", imageStr,
                "fileType", fileType,
                "fileName", fileName);

        result = productService.uploadCompanyImg(fileMap);
        //文件路径
        String path=proImagePath+fileName;
        //输出到文件路径下
        FileUtil.base64ToImage(imageStr,path);

        writeJson(result);
    }

3.工具层

/**
     * base64到图片
     *
     * @param imageStr
     * @param path
     */
    public static void base64ToImage(String imageStr, String path) {
          
   


        Base64.Decoder decoder = Base64.getDecoder();
        String baseValue = imageStr.replaceAll(" ", "+");
        byte[] data = decoder.decode(baseValue.replace("data:image/png;base64,", ""));


        /*byte[] data = decoder.decode(imageStr);*/
        if (data.length < 3 || StringUtils.isEmpty(path)) {
          
   
            return;
        }

//        File filedir = new File(StringUtils.substringBeforeLast(path, File.separator));
//        if (!filedir.exists()) {filedir.mkdirs();}
        try {
          
   
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            try {
          
   
                imageOutput.write(data, 0, data.length);
            } catch (Exception ex) {
          
   
                ex.printStackTrace();
            } finally {
          
   
                imageOutput.close();
            }
        } catch (Exception ex) {
          
   
            ex.printStackTrace();
        }
    }
经验分享 程序员 微信小程序 职场和发展