Linux安装go-fastdfs

安装

powershell 复制代码
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文件下载

使用

java 复制代码
@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());
        }
    }

}
java 复制代码
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();
    }
}

调用

java 复制代码
UploadResult upload = GoFastUtils.upload(file, null, "image", "http://192.168.3.193:8848/group1/upload");
相关推荐
疯狂的程需猿26 分钟前
一个百度、必应搜索引擎图片获取下载的工具包
golang·图搜索
萨格拉斯救世主35 分钟前
戴尔R930服务器增加 Intel X710-DA2双万兆光口含模块
运维·服务器
Jtti38 分钟前
Windows系统服务器怎么设置远程连接?详细步骤
运维·服务器·windows
TeYiToKu42 分钟前
笔记整理—linux驱动开发部分(9)framebuffer驱动框架
linux·c语言·arm开发·驱动开发·笔记·嵌入式硬件·arm
dsywws44 分钟前
Linux学习笔记之时间日期和查找和解压缩指令
linux·笔记·学习
yeyuningzi1 小时前
Debian 12环境里部署nginx步骤记录
linux·运维·服务器
上辈子杀猪这辈子学IT1 小时前
【Zookeeper集群搭建】安装zookeeper、zookeeper集群配置、zookeeper启动与关闭、zookeeper的shell命令操作
linux·hadoop·zookeeper·centos·debian
minihuabei1 小时前
linux centos 安装redis
linux·redis·centos
EasyCVR2 小时前
萤石设备视频接入平台EasyCVR多品牌摄像机视频平台海康ehome平台(ISUP)接入EasyCVR不在线如何排查?
运维·服务器·网络·人工智能·ffmpeg·音视频
明月看潮生2 小时前
青少年编程与数学 02-003 Go语言网络编程 09课题、Cookie
青少年编程·golang·网络编程·编程与数学