上传图片到指定路径工具类(非OSS)

2018-09-29  本文已影响0人  writeanewworld
// 如果从数据库中找不到已经存在的url,就直接上传图片,否则上传成功之后删除原图
    String oldPath = Optional.of(res)
            .map(CommonResult::getValues)
            .filter(brandInfos -> !brandInfos.isEmpty())
            .map(c -> c.get(0))
            .map(BrandInfo::getLogoUrl)
            .orElse(null);


    String[] endPath = picture.getContentType().split("/");

    //保存
    String fileName = UUID.randomUUID().toString() + "." + endPath[1];

    String url = filefolder + fileName;
    InputStream in = null;

    try {
        in = picture.getInputStream();
    }catch (IOException e){
        LOG.error("图片保存失败");
        return result;
    }   

public static boolean saveFile(String url, InputStream inputStream) {
    OutputStream outputStream = null;

    try {
        //判断文件是否为空
        if(inputStream==null || inputStream.available()==0){
            return false;
        }

        //保存文件
        outputStream = new FileOutputStream(url);
        byte[] buffer = new byte[1024];
        int len = 0;

        while((len = inputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,len);
        }

    }catch (IOException e){
        e.printStackTrace();
        return false;
    }finally {
        if(inputStream!=null){
            try {
                inputStream.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        if(outputStream!=null){
            try {
                outputStream.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }
    return true;
}

public static boolean deleteFile(String url) {
    File file = new File(url);
    try {
        file.delete();
    }catch (Exception e){
       return false;
    };

    return true;
}
上一篇下一篇

猜你喜欢

热点阅读