安装
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
下载速度巨慢,此处提供下载好的资源
使用
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");