|
@@ -0,0 +1,83 @@
|
|
|
+package com.caimei365.tools.service.impl;
|
|
|
+
|
|
|
+import com.caimei365.tools.model.ResponseJson;
|
|
|
+import com.caimei365.tools.service.UploadService;
|
|
|
+import com.caimei365.tools.utils.FastDfsUtil;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.http.HttpHeaders;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+import org.springframework.web.multipart.MultipartFile;
|
|
|
+
|
|
|
+import javax.annotation.Resource;
|
|
|
+import java.io.File;
|
|
|
+import java.io.IOException;
|
|
|
+import java.util.UUID;
|
|
|
+
|
|
|
+/**
|
|
|
+ * Description
|
|
|
+ *
|
|
|
+ * @author : Charles
|
|
|
+ * @date : 2021/10/25
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Service
|
|
|
+public class UploadServiceImpl implements UploadService {
|
|
|
+ @Value("${caimei.imageDomain}")
|
|
|
+ private String imageDomain;
|
|
|
+ @Value("${spring.cloud.config.profile}")
|
|
|
+ private String profile;
|
|
|
+ @Resource
|
|
|
+ private FastDfsUtil fastDfsUtil;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 图片上传
|
|
|
+ */
|
|
|
+ @Override
|
|
|
+ public ResponseJson<String> bulkImageUpload(MultipartFile[] file, HttpHeaders headers){
|
|
|
+ // 打印IP
|
|
|
+ String ip = headers.getFirst("X-CLIENT-IP");
|
|
|
+ log.info("【图片上传】 X-CLIENT-IP : " + ip);
|
|
|
+ if (file != null && file.length > 0) {
|
|
|
+ try {
|
|
|
+ StringBuilder fileUrl = new StringBuilder();
|
|
|
+ for (MultipartFile fileItem : file) {
|
|
|
+ String url = saveFile(fileItem);
|
|
|
+ fileUrl.append(imageDomain).append("/").append(url);
|
|
|
+ }
|
|
|
+ log.info("【图片上传】>>>>>>>>>>>>>>>>上传成功:" + fileUrl);
|
|
|
+ return ResponseJson.success("上传成功", fileUrl.toString());
|
|
|
+ } catch (IOException e) {
|
|
|
+ log.error("【图片上传】>>>>>>>>>>>>>>>>上传失败:" + e);
|
|
|
+ return ResponseJson.error("请传入图片!",null);
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ return ResponseJson.error("请传入图片!",null);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 保存文件
|
|
|
+ */
|
|
|
+ private String saveFile(MultipartFile file) throws IOException {
|
|
|
+ String originalFilename = file.getOriginalFilename();
|
|
|
+ String randomStr = UUID.randomUUID().toString();
|
|
|
+ assert originalFilename != null;
|
|
|
+ int index = originalFilename.lastIndexOf(".");
|
|
|
+ String name = originalFilename.substring(index);
|
|
|
+ String filePath = "/mnt/newdatadrive/data/runtime/cloud-instance/server-tools/";
|
|
|
+ if ("dev".equals(profile)){
|
|
|
+ filePath = "D:\\";
|
|
|
+ }
|
|
|
+ filePath += "\\" + randomStr + name;
|
|
|
+ // 临时图片
|
|
|
+ File tempFile = new File(filePath);
|
|
|
+ file.transferTo(tempFile);
|
|
|
+ log.info("【图片上传】>>>>>>>>>>>>>>>>图片临时路径:" + filePath);
|
|
|
+ String fileUrl = fastDfsUtil.uploadFile(filePath);
|
|
|
+ // 删除临时图片
|
|
|
+ boolean delete = tempFile.delete();
|
|
|
+ log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时图片:" + delete);
|
|
|
+ return fileUrl;
|
|
|
+ }
|
|
|
+}
|