默认

图片上传(黄图鉴定)

微信扫一扫,分享到朋友圈

图片上传(黄图鉴定)
收藏 0 0

Controller 接收file:      MultipartFile file

基础的过滤判断

if (file == null || file.getSize() == 0) {
   return ResultGenerator.genFailResult("上传文件不能为空");
}

MultipartFile 转 File

    /**
     * MultipartFile 转 File
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

图片鉴定黄图

        File toFile = FileUtil.multipartFileToFile(file);        
        boolean checkResult = true;
        if (RegexUtil.match("image\\/.*", FileUtil.getFileType(toFile))) {
            try {
                WxMaSecCheckService wxMaSecCheckService = wxService.getSecCheckService();
                checkResult = wxMaSecCheckService.checkImage(toFile);
            } catch (WxErrorException e) {
                //logger.error("图片鉴定异常", e);
                String message = e.getMessage();
                JSONObject obj = JSONObject.parseObject(message);
                if (87014 == obj.getInteger("errcode")) {
                    logger.error("图片鉴定异常", message);
                    checkResult = false;
                }
            }
        }
        if (!checkResult) {
            toFile.delete();
            return ResultGenerator.genFailResult("上传失败,图片含有违法违规内容~");
        }
        

111

   //判断是否为null
   private void assertSaveLocalFileFailed(File savedFile) {
        if (Objects.isNull(savedFile)) {
            throw new DataValidateException("", "save local file failed");
        }
    }

    //图片制定路径上传到本地
    public static final String uploadLocalDir = "/opt/tempuploadfile";
    private File saveLocalFile(MultipartFile file, String filePath) {
        File savedFile = null;
        try {
            String savedFilePath = uploadLocalDir + File.separator + filePath;
            savedFile = new File(savedFilePath);
            FileUtil.copyToFile(file.getInputStream(), savedFile);
        } catch (Exception e) {
            logger.error("save local file failed", e);
        }
        return savedFile;
    }

开始上传到云存储

        //删除文件MultipartFile 转 File 的文件
        toFile.delete();
        String fileName = getFileName(file);
        String filePath = getFilePath(fileName);
        //上传到本地
        File savedFile = saveLocalFile(file, filePath);
        //判断是否本地上传成功
        assertSaveLocalFileFailed(savedFile);

        // 判断是视频文件
        int begin = file.getOriginalFilename().indexOf(".");
        int last = file.getOriginalFilename().length();
        //获得文件后缀名
        String a = file.getOriginalFilename().substring(begin, last);

        //腾讯云存储
        String filepath = TencentUploadUtil.uploadFile(file);
        //file类型判断 返回
        Map<String, Object> data = new HashMap<>();
        data.put("filepath", filepath);
        if (a.endsWith(".mp4")) {
            data.put("filetype", "video/mp4");
        }else {
            data.put("filetype", "image/jpeg");
        }

同居类

public class TencentUploadUtil {

    public static Logger logger = LoggerFactory.getLogger(HttpRequest.class);

    public static final String appid = "13*****33";

    public static final String secretId = "AKIDJ*******************IZm1GF";

    public static final String secretKey = "ymIef******************vzmuO";

    public static final String bucket = "ap-chengdu";

    public static final String bucketName = "ldfr-13016****3";


    public static final String qianzui = "xxx";

    /**
     * 上传文件
     *
     * @param
     * @param file
     * @return 成功返回文件路径, 失败返回null
     */
    public static String uploadFile(MultipartFile file) {
        String relult = "";
        String oldFileName = file.getOriginalFilename();

        String eName = oldFileName.substring(oldFileName.lastIndexOf("."));

        //String newFileName = PropertiesUtils.getCommonYml("imagepath").toString() + UUID.randomUUID() + eName;

        String newFileName= UUID.randomUUID() + eName;

        Calendar cal = Calendar.getInstance();

        int year = cal.get(Calendar.YEAR);

        int month = cal.get(Calendar.MONTH) + 1;

        int day = cal.get(Calendar.DATE);

        // 1 初始化用户身份信息(secretId, secretKey)

        COSCredentials cred = new BasicCOSCredentials(appid, secretId, secretKey);


        ClientConfig clientConfig = new ClientConfig(new Region(bucket));

        // 3 生成cos客户端

        COSClient cosclient = new COSClient(cred, clientConfig);


        File localFile = null;

        try {
            localFile = File.createTempFile("temp", null);

            file.transferTo(localFile);

            // 指定要上传到 COS 上的路径

            String key = "/" + qianzui + "/" + year + "/" + month + "/" + day + "/" + newFileName;

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);

            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            relult = putObjectRequest.getKey();
        } catch (Exception e) {
            logger.error("上传文件失败", e);
        } finally {
            cosclient.shutdown();
        }
        localFile.delete();
        return relult;
    }

}
展开阅读全文
干一件事情,用心干就完了

你也可能喜欢

发表评论

您的电子邮件地址不会被公开。 必填项已用 * 标注

提示:点击验证后方可评论!

插入图片

分类目录

微信扫一扫

微信扫一扫