From fa10620c874c944f4b37ce15a6782d3d08d2a8da Mon Sep 17 00:00:00 2001
From: zhanghua <314079846@qq.com>
Date: 星期六, 10 九月 2022 21:29:35 +0800
Subject: [PATCH] 文件上传接口
---
ycl-common/src/main/java/com/ycl/dto/media/PictureZoomParameter.java | 29 +++
ycl-platform/src/main/resources/application-pro.yml | 15 +
ycl-platform/src/main/resources/application-dev.yml | 17 +
ycl-platform/src/main/java/com/ycl/controller/FileController.java | 53 +++++
server.sh | 95 ++++++++++
ycl-common/src/main/java/com/ycl/utils/MediaFileUtil.java | 259 ++++++++++++++++++++++++++++
pom.xml | 19 ++
ycl-common/src/main/java/com/ycl/dto/media/Media.java | 20 ++
8 files changed, 506 insertions(+), 1 deletions(-)
diff --git a/pom.xml b/pom.xml
index 747e79a..6e96dda 100644
--- a/pom.xml
+++ b/pom.xml
@@ -2,6 +2,18 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>16</source>
+ <target>16</target>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
@@ -101,6 +113,13 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
+ <!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
+ <dependency>
+ <groupId>com.github.tobato</groupId>
+ <artifactId>fastdfs-client</artifactId>
+ <version>1.27.2</version>
+ </dependency>
+
<!--Hutool Java宸ュ叿鍖�-->
<dependency>
<groupId>cn.hutool</groupId>
diff --git a/server.sh b/server.sh
new file mode 100644
index 0000000..998e02e
--- /dev/null
+++ b/server.sh
@@ -0,0 +1,95 @@
+#!/bin/bash
+#瀹氫箟鏈嶅姟鏁扮粍
+serviceArr=(ycl)
+#褰撳墠璺緞
+rootPath=$(pwd)
+#杈撳叆鎿嶄綔鏂瑰紡
+read -p "璇疯緭鍏ユ搷浣滄柟寮忓搴旂殑搴忓彿:
+1.start
+2.stop
+-> " action
+echo ----------------------------------------------------------------------------------
+#杈撳叆鎿嶄綔鏈嶅姟
+read -p "璇疯緭鍏ラ渶瑕佹搷浣滅殑鏈嶅姟瀵瑰簲鐨勫簭鍙�,璇蜂互绌烘牸鍒嗛殧:
+1.ycl
+-> "
+servers=$REPLY
+echo ----------------------------------------------------------------------------------
+#鍒ゆ柇鎿嶄綔
+if [ "$action" -eq 1 ];then
+ read -p "璇疯緭鍏ュ惎鍔ㄧ幆澧冨弬鏁�(濡備笉鎸囧畾,榛樿涓哄紑鍙戠幆澧�):
+dev-寮�鍙戠幆澧�
+prod-鐢熶骇鐜
+test-鏈湴娴嬭瘯鐜
+onlinetest-绾夸笂娴嬭瘯鐜
+-> " env
+echo ----------------------------------------------------------------------------------
+ if [ -n "$env" ];then
+ envConfig="--spring.profiles.active="${env}
+ fi
+ for i in $servers
+ do
+ if [ $i -gt 1 ];then
+ echo 杈撳叆鐨勬湇鍔″簭鍙疯繃澶�
+ elif [ $i -lt 1 ];then
+ echo 杈撳叆鐨勬湇鍔″簭鍙疯繃灏�
+ else
+ i=$(($i-1))
+ echo 姝e湪鍚姩鏈嶅姟 ${serviceArr[$i]}
+ cd $rootPath/${serviceArr[$i]}
+ # java鍚姩鍙傛暟 $startConfig
+ #-Xms128m 鏈�灏忓爢
+ #-Xmx256m 鏈�澶у爢 姝ゅ�煎彲浠ヨ缃笌-Xms鐩稿悓锛屼互閬垮厤姣忔鍨冨溇鍥炴敹瀹屾垚鍚嶫VM閲嶆柊鍒嗛厤鍐呭瓨
+ #-Xmn2g 骞磋交浠�
+ #-Xss128k 绾跨▼鍫嗗ぇ灏廰
+ #BackManager閰嶇疆
+ if [[ $serviceArr[$i] =~ "ycl" ]];then
+ startConfig="-Xms400m -Xmx400m"
+ else
+ startConfig="-Xms400m -Xmx400m"
+ fi
+ echo 鍦ㄨ矾寰� $(pwd) 涓�
+ echo 鎵ц nohup java $startConfig -jar *.jar $envconfig "&"
+ nohup java $startConfig -jar *.jar $envConfig &
+ pid=$(ps -ef|grep -i ${serviceArr[$i]}|grep .jar|grep -v grep|awk '{print $2}')
+ if [ -n "$pid" ];then
+ echo 鍚姩鏈嶅姟 ${serviceArr[$i]} 鎴愬姛,杩涚▼ID涓�: $pid
+ else
+ echo 鍚姩鏈嶅姟 ${serviceArr[$i]} 澶辫触,鎵ц鐨勫懡浠や负:
+ echo nohup java $startConfig -jar *.jar $envconfig &
+ fi
+ echo ----------------------------------------------------------------------------------
+ fi
+ done
+elif [ "$action" -eq 2 ];then
+ for i in $servers
+ do
+ if [ $i -gt 1 ];then
+ echo 杈撳叆鐨勬湇鍔″簭鍙疯繃澶�
+ elif [ $i -lt 1 ];then
+ echo 杈撳叆鐨勬湇鍔″簭鍙疯繃灏�
+ else
+ i=$(($i-1))
+ pid=$(ps -ef|grep -i ${serviceArr[$i]}|grep .jar|grep -v grep|awk '{print $2}')
+ serverName=$(ps -ef|grep -i ${serviceArr[$i]}|grep .jar|grep -v grep|awk '{print $12}')
+ if [ -n "$pid" ];then
+ echo 鍏抽棴鏈嶅姟 ${serviceArr[$i]} 鐨勮繘绋婭D涓�: $pid
+ echo 鍏抽棴鏈嶅姟 ${serviceArr[$i]} 鐨刯ar鍖呭悕涓�: $serverName
+ kill -9 $pid
+ result=$(ps -ef|grep $pid|grep -v grep)
+ if [ -n "$result" ];then
+ echo 鍏抽棴鏈嶅姟鎴愬姛!
+ else
+ echo 鍏抽棴鏈嶅姟澶辫触! 鏌ヨ鍒扮殑杩涚▼涓�:
+ echo $result
+ echo 璇烽噸鏂板皾璇�!
+ fi
+ else
+ echo 鏈惎鍔ㄦ湇鍔� ${serviceArr[$i]}
+ fi
+ echo ----------------------------------------------------------------------------------
+ fi
+ done
+else
+ echo 杈撳叆鐨勬搷浣滄柟寮忔湁璇�,璇烽噸鏂版墽琛岃剼鏈�!
+fi
diff --git a/ycl-common/src/main/java/com/ycl/dto/media/Media.java b/ycl-common/src/main/java/com/ycl/dto/media/Media.java
new file mode 100644
index 0000000..8a463fb
--- /dev/null
+++ b/ycl-common/src/main/java/com/ycl/dto/media/Media.java
@@ -0,0 +1,20 @@
+package com.ycl.dto.media;
+
+import lombok.Data;
+
+@Data
+public class Media {
+ private String type;//绫诲瀷
+
+ private String def; //瑙嗛榛樿鍥剧墖
+
+ private String url1; //灏�
+
+ private String url2; //涓�
+
+ private String url3;//澶�
+
+ private String url4; //鏈�澶э紙鏆傛椂涓嶄娇鐢�)
+
+ private Integer sort;//闆嗗悎涓殑鎺掑簭
+}
diff --git a/ycl-common/src/main/java/com/ycl/dto/media/PictureZoomParameter.java b/ycl-common/src/main/java/com/ycl/dto/media/PictureZoomParameter.java
new file mode 100644
index 0000000..6084aab
--- /dev/null
+++ b/ycl-common/src/main/java/com/ycl/dto/media/PictureZoomParameter.java
@@ -0,0 +1,29 @@
+package com.ycl.dto.media;
+
+
+import lombok.Data;
+
+/**
+ * 鍥剧墖缂╂斁鍙傛暟
+ */
+@Data
+public class PictureZoomParameter {
+
+ public static final PictureZoomParameter getBoardPar(){
+ PictureZoomParameter par =new PictureZoomParameter();
+ par.setWidth1(300);
+ par.setWidth2(600);
+ par.setWidth3(1200);
+ return par;
+ }
+
+
+ private Integer width1;
+
+ private Integer width2;
+
+ private Integer width3;
+
+ private Integer width4;
+
+}
diff --git a/ycl-common/src/main/java/com/ycl/utils/MediaFileUtil.java b/ycl-common/src/main/java/com/ycl/utils/MediaFileUtil.java
new file mode 100644
index 0000000..c89c30d
--- /dev/null
+++ b/ycl-common/src/main/java/com/ycl/utils/MediaFileUtil.java
@@ -0,0 +1,259 @@
+package com.ycl.utils;
+
+
+import com.github.tobato.fastdfs.domain.fdfs.StorePath;
+import com.github.tobato.fastdfs.domain.upload.FastImageFile;
+import com.github.tobato.fastdfs.service.FastFileStorageClient;
+import com.ycl.dto.media.PictureZoomParameter;
+import com.ycl.dto.media.Media;
+import net.coobird.thumbnailator.Thumbnails;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.PostConstruct;
+import java.awt.image.BufferedImage;
+import java.io.*;
+import java.time.format.DateTimeFormatter;
+import java.util.List;
+import java.util.regex.Pattern;
+
+@Component
+public class MediaFileUtil {
+
+
+ private static MediaFileUtil self;
+ @Value("${fdfs.groupName}")
+ private String groupName;
+
+ @PostConstruct
+ private void init() {
+ self = this;
+ }
+
+
+ @Autowired
+ private FastFileStorageClient storageClient;
+
+
+ private static final Pattern videoPattern = Pattern.compile("((mp4|flv|avi|rm|rmvb|wmv)(jpg|png|gif|bmp))");
+
+ @Value("${cfg.res}")
+ private String rootPath;
+
+ private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMM");
+
+
+ public MediaFileUtil() throws IOException {
+
+ }
+
+
+ public static String uploadImage(InputStream in) throws IOException {
+
+ return self.storageClient.uploadImage(new FastImageFile(in, in.available(), "jpg", null)).getFullPath();
+ }
+
+
+ public static String uploadImage(File file) throws IOException {
+
+ FileInputStream in = new FileInputStream(file);
+ return self.storageClient.uploadImage(new FastImageFile(in, in.available(), "jpg", null)).getFullPath();
+ }
+
+
+ /**
+ * 鍒ゆ柇鏂囦欢绫诲瀷
+ *
+ * @param fileName
+ * @return
+ */
+ public Short getType(String fileName) {
+
+ String ext = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
+
+ if (".jpg".equals(ext) || ".jpeg".equals(ext) || ".png".equals(ext) || ".gif".equals(ext) || ".bmp".equals(ext)) {
+ return 1;
+ } else if (".mp4".equals(ext) || ".avi".equals(ext) || ".flv".equals(ext) || ".rm".equals(ext) || ".wmv".equals(ext)) {
+ return 2;
+ } else {
+ return 0;
+ }
+ }
+
+ public Media save(MultipartFile file, PictureZoomParameter zoomPar) throws Exception {
+ String[] fs = file.getOriginalFilename().split("\\.");
+ String ext = fs[fs.length - 1];
+
+ switch (this.getType(file.getOriginalFilename())) {
+ case 1:
+ return this.savePicture(file, ext, zoomPar);
+ case 2:
+ return this.saveVideo(file, ext);
+ default:
+ return new Media();
+ }
+ }
+
+
+ public Media savePicture(MultipartFile file, String ext, PictureZoomParameter zoomPar) throws Exception {
+
+ ByteArrayOutputStream outs = new ByteArrayOutputStream();
+ Media media = new Media();
+ media.setType(ext);
+ String path = null;
+ if (zoomPar.getWidth1() != null && zoomPar.getWidth1() > 0) {
+ path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth1());
+ media.setUrl1(path);
+ }
+ if (zoomPar.getWidth2() != null && zoomPar.getWidth2() > 0) {
+ path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth2());
+ media.setUrl2(path);
+ }
+ if (zoomPar.getWidth3() != null && zoomPar.getWidth3() > 0) {
+ path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth3());
+ media.setUrl3(path);
+ }
+ // width4涓哄師鍥�
+ path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth4());
+ media.setUrl4(path);
+ return media;
+ }
+
+ /**
+ * 淇濆瓨瑙嗛鏂囦欢
+ *
+ * @param file
+ * @param ext
+ * @return
+ * @throws Exception
+ */
+ public Media saveVideo(MultipartFile file, String ext) throws Exception {
+// StorePath sp = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
+
+ StorePath sp = storageClient.uploadFile(groupName, file.getInputStream(), file.getSize(), ext);
+ Media media = new Media();
+ media.setType(ext);
+ media.setUrl1(sp.getFullPath());
+ return media;
+ }
+
+ /**
+ * 鍒犻櫎涓�涓枃浠�
+ *
+ * @param rootPath
+ */
+ public void removeFile(String rootPath) {
+ storageClient.deleteFile(rootPath);
+ }
+
+ public void removeMedia(Media media) {
+ if (!StringUtils.isEmpty(media.getUrl1())) {
+ storageClient.deleteFile(media.getUrl1());
+ }
+ if (!StringUtils.isEmpty(media.getUrl2())) {
+ storageClient.deleteFile(media.getUrl2());
+ }
+ if (!StringUtils.isEmpty(media.getUrl3())) {
+ storageClient.deleteFile(media.getUrl3());
+ }
+ if (!StringUtils.isEmpty(media.getUrl4())) {
+ storageClient.deleteFile(media.getUrl4());
+ }
+ }
+
+
+ public void removeMedias(List<Media> medias) {
+ if (medias != null) {
+ for (Media m : medias) {
+ if (!StringUtils.isEmpty(m.getUrl1())) {
+ storageClient.deleteFile(m.getUrl1());
+ }
+ if (!StringUtils.isEmpty(m.getUrl2())) {
+ storageClient.deleteFile(m.getUrl2());
+ }
+ if (!StringUtils.isEmpty(m.getUrl3())) {
+ storageClient.deleteFile(m.getUrl3());
+ }
+ if (!StringUtils.isEmpty(m.getUrl4())) {
+ storageClient.deleteFile(m.getUrl4());
+ }
+ }
+ }
+
+ }
+
+ /**
+ * 鍒ゆ柇鏂囦欢鏄惁瀛樺湪
+ *
+ * @param url
+ * @return
+ */
+ public Boolean isEmpty(String url) {
+ return true;
+ }
+
+ /**
+ * 缂╂斁骞朵笖涓婁紶
+ *
+ * @param in
+ * @param ext
+ * @param width
+ * @return
+ * @throws Exception
+ */
+ private String thumbAndStorage(InputStream in, String ext, Integer width) throws Exception {
+
+ Thumbnails.Builder fileBuilder = Thumbnails.of(in).scale(1.0).outputQuality(1.0);
+ BufferedImage src = fileBuilder.asBufferedImage();
+
+ Integer w = src.getWidth(null);
+ Integer destWidth = width > w ? w : width;
+
+ ByteArrayOutputStream bouts = new ByteArrayOutputStream();
+ Thumbnails.of(in).width(destWidth).toOutputStream(bouts);
+ InputStream ins = this.out2In(bouts);
+
+ StorePath sp = storageClient.uploadFile(groupName, ins, bouts.size(), ext);
+// StorePath sp = storageClient.uploadFile(ins, bouts.size(), ext, null);
+ bouts.close();
+ ins.close();
+ return sp.getFullPath();
+ }
+
+ private String thumbAndStorageOfFile(MultipartFile file, String ext, Integer width) throws Exception {
+
+ Thumbnails.Builder fileBuilder = Thumbnails.of(file.getInputStream()).scale(1.0).outputQuality(1.0);
+ BufferedImage src = fileBuilder.asBufferedImage();
+
+ Integer w = src.getWidth(null);
+ Integer destWidth = width == null || width > w ? w : width;
+
+ ByteArrayOutputStream bouts = new ByteArrayOutputStream();
+ Thumbnails.of(file.getInputStream()).width(destWidth).toOutputStream(bouts);
+ InputStream ins = this.out2In(bouts);
+ StorePath sp = storageClient.uploadFile(groupName, ins, bouts.size(), ext);
+// StorePath sp = storageClient.uploadFile(ins, bouts.size(), ext, null);
+ bouts.close();
+ ins.close();
+ return sp.getFullPath();
+ }
+
+
+ /**
+ * 杈撳嚭娴佽浆杈撳叆娴�
+ *
+ * @param outs
+ * @return
+ * @throws Exception
+ */
+ private InputStream out2In(ByteArrayOutputStream outs) throws Exception {
+ InputStream ins = new ByteArrayInputStream(outs.toByteArray());
+
+ return ins;
+ }
+
+
+}
diff --git a/ycl-platform/src/main/java/com/ycl/controller/FileController.java b/ycl-platform/src/main/java/com/ycl/controller/FileController.java
new file mode 100644
index 0000000..9592f8c
--- /dev/null
+++ b/ycl-platform/src/main/java/com/ycl/controller/FileController.java
@@ -0,0 +1,53 @@
+package com.ycl.controller;
+
+import com.ycl.api.CommonResult;
+import com.ycl.dto.media.Media;
+import com.ycl.dto.media.PictureZoomParameter;
+import com.ycl.utils.MediaFileUtil;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+@RestController
+@Api(tags = "鏂囦欢涓婁紶")
+@RequestMapping("/file")
+public class FileController {
+ @Autowired
+ private MediaFileUtil mediaFileUtil;
+
+ /**
+ * 涓婁紶鍥剧墖
+ *
+ * @param file
+ * @return
+ */
+
+ @ApiOperation("涓婁紶鍥剧墖")
+ @RequestMapping(value = "/medias", method = RequestMethod.POST)
+ public CommonResult<Media> mediaUpload(@RequestParam("file") MultipartFile file) {
+ try {
+ PictureZoomParameter zoomPar = PictureZoomParameter.getBoardPar();
+ Media res = mediaFileUtil.save(file, zoomPar);
+
+ return CommonResult.success(res, "ok");
+ } catch (Exception e) {
+ return CommonResult.failed("fail!");
+ }
+ }
+
+ @ApiOperation("鍒犻櫎鍥剧墖")
+ @RequestMapping(value = "media/delete", method = RequestMethod.DELETE)
+ public CommonResult<Boolean> delete(@RequestBody Media media) {
+ try {
+ mediaFileUtil.removeMedia(media);
+
+ return CommonResult.success(true, "ok");
+ } catch (Exception e) {
+ return CommonResult.failed("fail!");
+ }
+
+ }
+
+}
diff --git a/ycl-platform/src/main/resources/application-dev.yml b/ycl-platform/src/main/resources/application-dev.yml
index 582766f..9cd2e9a 100644
--- a/ycl-platform/src/main/resources/application-dev.yml
+++ b/ycl-platform/src/main/resources/application-dev.yml
@@ -1,10 +1,25 @@
server:
- port: 8081
+ port: 8082
tomcat:
uri-encoding: UTF-8
servlet:
context-path: /sccg
compression: true
+
+fdfs:
+ groupName: sczhzf
+ soTimeout: 1500
+ connectTimeout: 600
+ trackerList: #TrackerList鍙傛暟,鏀寔澶氫釜
+ - 140.143.152.226:22122
+
+cfg:
+ res: d://resources
+ media-res: 140.143.152.226/media/
+ snow-flake:
+ datacenterId: 1
+ machineId: 1
+
spring:
redis:
database: 0
diff --git a/ycl-platform/src/main/resources/application-pro.yml b/ycl-platform/src/main/resources/application-pro.yml
index ce02925..8e9bc9c 100644
--- a/ycl-platform/src/main/resources/application-pro.yml
+++ b/ycl-platform/src/main/resources/application-pro.yml
@@ -5,6 +5,21 @@
servlet:
context-path: /sccg
compression: true
+
+fdfs:
+ groupName: sczhzf
+ soTimeout: 1500
+ connectTimeout: 600
+ trackerList: #TrackerList鍙傛暟,鏀寔澶氫釜
+ - 140.143.152.226:22122
+ -
+cfg:
+ res: d://resources
+ media-res: 140.143.152.226/media/
+ snow-flake:
+ datacenterId: 1
+ machineId: 1
+
spring:
redis:
database: 0
--
Gitblit v1.8.0