当前位置: 首页 > article >正文

Linux安装go-fastdfs

安装

mkdir /home/go-fastdfs
wget -P /home/go-fastdfs https://github.com/sjqzhang/go-fastdfs/releases/download/v1.4.5/fileserver
chmod +x /home/go-fastdfs/fileserver
cd /home/go-fastdfs
nohup ./fileserver server  &

由于fileserver下载速度巨慢,此处提供下载好的资源

fileserver文件下载

使用

@Component
public class GoFastUtils {
    private static final Logger logger = LoggerFactory.getLogger(GoFastUtils.class);

    /**
     * 返回数据输出格式,json|text|json2
     */
    private static final String OUTPUT = "json";

    public static String[] imageType = {"jpg", "jpeg", "png"};
    public static String[] videoType = {"mp4", "avi"};

    /**
     * 判断文件类型 <br/>
     * 文件类型: jpg
     */
    public static boolean isOkFileType(@NotNull MultipartFile file, @NotNull String fileType) throws IOException {
        String type = FileTypeUtil.getType(file.getInputStream());
        logger.info("file-type:{}", type);
        return type.equalsIgnoreCase(fileType);
    }

    public static boolean isJpg(@NotNull MultipartFile file) throws IOException {
        String type = FileTypeUtil.getType(file.getInputStream());
        logger.info("file-type:{}", type);
        return type.equalsIgnoreCase("jpg");
    }

    /**
     * 上传文件
     *
     * @param file
     * @param path       自定义路径
     * @param scene      场景
     * @param serverAddr
     * @return
     * @throws Exception
     */
	public static UploadResult upload(MultipartFile file, String path, String scene, String serverAddr)
			throws IOException {
		String resp = "";
		InputStream fileStream = null;
		String filename = "";
		try {
			fileStream = file.getInputStream();
			String originalFilename = file.getOriginalFilename();
			if ("blob".equals(originalFilename)) {
				originalFilename = extractFilename(file);
			}
			InputStreamResource isr = new InputStreamResource(fileStream, originalFilename);
			filename = isr.getName();
			// 请求参数
			Map<String, Object> params = new HashMap<>();
			params.put("file", isr);
			params.put("output", "json");
			params.put("path", path);
			params.put("scene", scene);
			resp = HttpRequest.post(serverAddr).form(params).timeout(90000).execute().body();
		} catch (Exception e) {
			throw new ValidatorException("文件上传发生异常,原因:" + e.getMessage());
		} finally {
			if (fileStream != null) {
				fileStream.close();
			}
		}
        JSONObject jsonObject = JSON.parseObject(resp);
        if("fail".equals(jsonObject.getString("status"))){
            throw new RuntimeException(jsonObject.getString("message"));
        }
        UploadResult result = JSONObject.parseObject(resp, UploadResult.class);
		result.setFilename(filename);
		if (!result.isSuccess()) {
			throw new RuntimeException("文件上传失败,原因:" + result.getRetmsg());
		}
        return result;
    }

	/**
	 * 编码文件名
	 */
	public static String extractFilename(MultipartFile file) {
		return StringUtils.format("{}_{}.{}", FilenameUtils.getBaseName(file.getOriginalFilename()),
				Seq.getId(Seq.uploadSeqType), getExtension(file));
	}
	/**
	 * 获取文件名的后缀
	 *
	 * @param file
	 *            表单文件
	 * @return 后缀名
	 */
	public static String getExtension(MultipartFile file) {
		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
		if (StringUtils.isEmpty(extension)) {
			extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
		}
		return extension;
	}

    /**
     * 图片上传(带水印)
     *
     * @param file
     * @param watermark 水印文字
     * @return
     * @throws IOException
     */
    public static UploadResult uploadWithWatermark(MultipartFile file, String watermark, String suffix)
            throws IOException {
        UploadResult uploadResult;
        ByteArrayOutputStream bos = addWatermark(file, watermark);
        byte[] b = bos.toByteArray();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(b);
        InputStreamResource isr = new InputStreamResource(byteArrayInputStream, file.getOriginalFilename());
        Map<String, Object> params = new HashMap<>();
        params.put("file", isr);
        params.put("path", "image");
        params.put("output", OUTPUT);
        params.put("scene", "image");

        String resp = HttpUtil.post(suffix, params);
        logger.info("GoFastDFSUtils2:uploadWithWatermark:resp: {}", resp);
        JSONObject exJson = JSONObject.parseObject(resp);
        uploadResult = JSON.toJavaObject(exJson, UploadResult.class);
        return uploadResult;
    }

    /**
     * 加水印
     *
     * @param file
     * @param watermark
     * @return
     * @throws IOException
     */
    private static ByteArrayOutputStream addWatermark(MultipartFile file, String watermark) throws IOException {
        InputStream in = file.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(in);
        BufferedImage image = ImageIO.read(bis);
        int height = image.getHeight();
        int width = image.getWidth();
        // 加水印
        Graphics2D g = image.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);
        g.setColor(new Color(128, 128, 128));
        // 字体大小
        int num = width > height ? height / 30 : width / 30;

        g.setFont(new Font("微软雅黑", Font.PLAIN, num));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = formatter.format(new Date());
        String[] rows = {date, watermark};
        // 设置水印坐标,左上角为起点
        int x = 10;
        int y = height - 5;
        for (String row : rows) {
            g.drawString(row, x, y -= g.getFontMetrics().getHeight() + 2);
        }
        g.dispose();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", bos);
        return bos;
    }

    /**
     * 图片删除
     */
    public static void deleteImage(String md5, String suffix) {
        if (StringUtils.isEmpty(md5)) {
            return;
        }
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("md5", md5);
            HttpUtil.post(suffix, params);
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
    }

}

public class UploadResult implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 文件访问路径
     */
    private String url;
    /**
     * md5码
     */
    private String md5;
    /**
     * 文件存储路径
     */
    private String path;
    /**
     * 域名:http://192.168.0.198:8080
     */
    private String domain;
    /**
     * 场景
     */
    private String scene;
    private String scenes;
    /**
     * 文件大小
     */
    private BigInteger size;
    private BigInteger mtime;
    /**
     * 返回结果消息
     */
    private String retmsg;
    /**
     * 返回结果状态编码
     */
    private int retcode;
    /**
     * 文件存储路径
     */
    private String src;

	/**
	 * 文件名
	 */
	private String filename;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getMd5() {
        return md5;
    }

    public void setMd5(String md5) {
        this.md5 = md5;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getScene() {
        return scene;
    }

    public void setScene(String scene) {
        this.scene = scene;
    }

    public BigInteger getSize() {
        return size;
    }

    public void setSize(BigInteger size) {
        this.size = size;
    }

    public BigInteger getMtime() {
        return mtime;
    }

    public void setMtime(BigInteger mtime) {
        this.mtime = mtime;
    }

    public String getScenes() {
        return scenes;
    }

    public void setScenes(String scenes) {
        this.scenes = scenes;
    }

    public String getRetmsg() {
        return retmsg;
    }

    public void setRetmsg(String retmsg) {
        this.retmsg = retmsg;
    }

    public int getRetcode() {
        return retcode;
    }

    public void setRetcode(int retcode) {
        this.retcode = retcode;
    }

    public String getSrc() {
        return src;
    }

    public void setSrc(String src) {
        this.src = src;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    /**
     * 是否上传成功
     *
     * @return
     */
    public boolean isSuccess() {
        return retcode == 0;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("UploadResult{");
        sb.append("url='").append(url).append('\'');
        sb.append(", md5='").append(md5).append('\'');
        sb.append(", path='").append(path).append('\'');
        sb.append(", domain='").append(domain).append('\'');
        sb.append(", scene='").append(scene).append('\'');
        sb.append(", scenes='").append(scenes).append('\'');
        sb.append(", size=").append(size);
        sb.append(", mtime=").append(mtime);
        sb.append(", retmsg='").append(retmsg).append('\'');
        sb.append(", retcode=").append(retcode);
        sb.append(", src='").append(src).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

调用

UploadResult upload = GoFastUtils.upload(file, null, "image", "http://192.168.3.193:8848/group1/upload");

http://www.kler.cn/a/324992.html

相关文章:

  • 【GPTs】Ai-Ming:AI命理助手,个人运势与未来发展剖析
  • 【网络云计算】2024第48周-技能大赛-初赛篇
  • 退款成功订阅消息点击后提示订单不存在
  • java语言特性(持续更新)
  • django-ninja 实现cors跨域请求
  • 理解 Python 中的 __getitem__ 方法:在自定义类中启用索引和切片操作
  • 编译安装的 Nginx 设置为服务启动
  • 基于mediapipe深度学习算法的手势数字0-9识别系统python源码+精美GUI界面
  • 9-pg内核之锁管理器(四)常规锁
  • [前端]DOM+CSS+HTML实现水波进度效果
  • SpringBoot 流式输出时,正常输出后为何突然报错?
  • 使用Prometheus进行系统监控,包括Mysql、Redis,并使用Grafana图形化表示
  • JVM和GC监控技术
  • 前端html+css+js 基础总结
  • Ubuntu24.04 yum安装
  • Android问题笔记五十:构建错误-AAPT2 aapt2-7.0.2-7396180-windows Daemon
  • “滑动窗口”思想在算法里面的应用
  • llama3.1 8b instruct的function calling的template解析
  • C++第五讲(1):STL--string--各个函数的使用方法
  • 在线支付系统
  • 无人机之模拟图传篇
  • 交互式低延迟音频解码器
  • QT开发:基于Qt实现的交通信号灯模拟器:实现一个带有倒计时功能的图形界面应用
  • 计算机毕业设计之:宠物互助平台的微信小程序系统(源码+文档+讲解)
  • Java | Leetcode Java题解之第429题N叉树的层序遍历
  • Go 语言框架接入阿里云的报警通知与日志实时追踪与监控