ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringBoot整合zimg图片服务器

2021-11-26 15:34:31  阅读:116  来源: 互联网

标签:SpringBoot import zimg springframework org apache 服务器 md5 String


 

依赖

  <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>


        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
        </dependency>

也有

  <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

 

yml配置

zimg:
  server: http://192.168.80.135:4869

 

ZimgConfig.java

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
public class ZimgConfig {
    @Value("${zimg.server}")
    private String zimgServer;


}

 

ZimgUtils.java

import com.example.zimg.config.ZimgConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;

/**
 * zimg工具类
 *
 */
@Component
@Slf4j
public class ZimgUtils {


    @Autowired
    private ZimgConfig zimgConfig;

    public static ZimgUtils zimgUtils;

    /**
     * 初始化minio配置
     */
    @PostConstruct
    public void init() {
        zimgUtils = this;
        zimgUtils.zimgConfig = this.zimgConfig;
    }

    private static final String uploadPath = "/upload";
    private static final String deletePath = "/admin";


    /**
     * 成功返回:
     * {
     * "ret": true,
     * "info": {
     * "md5": "a48998d3095079c71d1c72054b847dcf",
     * "size": 110823
     * }
     * }
     * <p>
     * 失败返回:
     * {
     * "ret": false,
     * "error": {
     * "code": 5,
     * "message": "Content-Length error."
     * }
     * }
     *
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public String uploadImage(MultipartFile multipartFile) throws Exception {
        String url = zimgConfig.getZimgServer() + uploadPath;
        String fileName = multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        //创建post请求对象
        HttpPost post = new HttpPost(url);
        //文件类型
        post.addHeader("Content-Type", ext.toLowerCase());
        ByteArrayEntity byteArrayEntity = null;
        byteArrayEntity = new ByteArrayEntity(multipartFile.getBytes());

        post.setEntity(byteArrayEntity);
        CloseableHttpClient client = HttpClients.createDefault();
        //启动执行请求,并获得返回值
        CloseableHttpResponse response = client.execute(post);
        //得到返回的entity对象
        HttpEntity entity = response.getEntity();
        //把实体对象转换为string
        String result = EntityUtils.toString(entity, "UTF-8");
        return result;
    }

    /**
     * 需要zimg的配置开启权限
     * 修改配置文件 zimg.lua 修改 admin_rule='allow 127.0.0.1' =》 admin_rule='allow all'
     */
    public void deleteImage(String md5) throws Exception {
        String url = zimgConfig.getZimgServer() + deletePath;

        //创建URLBuilder
        URIBuilder uriBuilder = new URIBuilder(url);
        //设置参数
        uriBuilder.setParameter("md5", md5);
        uriBuilder.setParameter("t", "1");
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        CloseableHttpClient client = HttpClients.createDefault();
        //启动执行请求,并获得返回值
        CloseableHttpResponse response = client.execute(httpGet);
        //得到返回的entity对象
        HttpEntity entity = response.getEntity();
        //把实体对象转换为string 这返回的html页面代码,,没找到json方式
        String result = EntityUtils.toString(entity, "UTF-8");
        log.info(result);
    }


}

 

使用

import com.alibaba.fastjson.JSONObject;
import com.example.zimg.utils.ZimgUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * demo控制器
 */
@RestController
@Slf4j
public class ZimgController {

    @Autowired
    private ZimgUtils zimgUtils;

    /**
     * 上传附件
     * @param file
     * @return
     */
    @PostMapping(value = "/upload")
    public void uploadImage(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                log.error(">>>>>>>>>>>>>>文件为空");
                return;
            }
            String s = zimgUtils.uploadImage(file);
            JSONObject object = JSONObject.parseObject(s);
            if (object.getBoolean("ret")){
                //成功
                JSONObject info = object.getJSONObject("info");
                log.info(">>>>>>>>> 文件md5:{},文件大小:{}",info.get("md5"),info.get("size"));
            }else {
                //失败
                JSONObject error = object.getJSONObject("error");
                log.error(">>>>>>>> 文件上传失败:{}",error.get("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除文件
     * @param md5 上传成功后返回的md5
     * @return
     */
    @DeleteMapping(value = "/delete")
    public void deleteImage(String md5) {
        try {
            zimgUtils.deleteImage(md5);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

标签:SpringBoot,import,zimg,springframework,org,apache,服务器,md5,String
来源: https://www.cnblogs.com/pxblog/p/15608031.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有