BackendFileController.java 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. package com.fuint.module.backendApi.controller;
  2. import com.aliyun.oss.OSS;
  3. import com.fuint.common.dto.AccountInfo;
  4. import com.fuint.common.service.SettingService;
  5. import com.fuint.common.util.AliyunOssUtil;
  6. import com.fuint.common.util.CommonUtil;
  7. import com.fuint.common.util.DateUtil;
  8. import com.fuint.common.util.TokenUtil;
  9. import com.fuint.framework.web.BaseController;
  10. import com.fuint.framework.web.ResponseObject;
  11. import com.fuint.utils.StringUtil;
  12. import io.swagger.annotations.Api;
  13. import io.swagger.annotations.ApiOperation;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.util.ResourceUtils;
  16. import org.springframework.web.bind.annotation.CrossOrigin;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import org.springframework.web.bind.annotation.RequestMethod;
  19. import org.springframework.web.bind.annotation.RestController;
  20. import org.springframework.web.multipart.MultipartFile;
  21. import org.springframework.web.multipart.MultipartHttpServletRequest;
  22. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;
  24. import org.springframework.core.env.Environment;
  25. import javax.servlet.http.HttpServletRequest;
  26. import java.io.File;
  27. import java.util.Date;
  28. import java.util.HashMap;
  29. import java.util.Map;
  30. import java.util.UUID;
  31. /**
  32. * 文件上传管理控制类
  33. *
  34. * Created by FSQ
  35. * CopyRight https://www.fuint.cn
  36. */
  37. @Api(tags="管理端-文件上传相关接口")
  38. @RestController
  39. @RequestMapping(value = "/backendApi/file")
  40. public class BackendFileController extends BaseController {
  41. private static final Logger logger = LoggerFactory.getLogger(BackendFileController.class);
  42. @Autowired
  43. private Environment env;
  44. @Autowired
  45. private SettingService settingService;
  46. /**
  47. * 后台上传文件
  48. *
  49. * @param request
  50. * @throws
  51. */
  52. @ApiOperation(value = "后台上传文件")
  53. @RequestMapping(value = "/upload", method = RequestMethod.POST)
  54. @CrossOrigin
  55. public ResponseObject uploadFileLocal(HttpServletRequest request) {
  56. String token = request.getHeader("Access-Token");
  57. String action = request.getParameter("action") == null ? "" : request.getParameter("action");
  58. AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
  59. if (accountInfo == null) {
  60. return getFailureResult(1001, "请先登录");
  61. }
  62. if (action.equals("config")) {
  63. Map<String, Object> outParams = new HashMap();
  64. outParams.put("imageActionName", "upload");
  65. outParams.put("fileActionName", "upload");
  66. outParams.put("fileFieldName", "file");
  67. outParams.put("imageFieldName", "file");
  68. outParams.put("fileUrlPrefix", "");
  69. outParams.put("imageUrlPrefix", "");
  70. return getSuccessResult(outParams);
  71. }
  72. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  73. String sourcePic = request.getParameter("sourcePic");// 页面图片元素的ID
  74. MultipartFile file = multipartRequest.getFile(sourcePic);
  75. if (file == null) {
  76. Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
  77. if (fileMap.size() > 0) {
  78. file = fileMap.get("file");
  79. }
  80. }
  81. Map<String, String> resultMap = new HashMap<>();
  82. String originalFilename = file.getOriginalFilename();
  83. if (StringUtil.isEmpty(originalFilename)) {
  84. return getFailureResult(201, "上传出错啦");
  85. }
  86. String maxSizeStr = env.getProperty("images.upload.maxSize");
  87. // 默认限制2M
  88. float maxSize = 2;
  89. try {
  90. maxSize = Float.parseFloat(maxSizeStr);
  91. } catch (NumberFormatException e) {
  92. logger.error("图片允许的大小设置不正确", e);
  93. }
  94. if (file.getSize() > (maxSize * 1024 * 1024)) {
  95. return getFailureResult(201, "上传的图片不能大于" + maxSize + "MB");
  96. }
  97. String fileType = file.getContentType();
  98. if (fileType.indexOf("image") == -1) {
  99. return getFailureResult(201, "上传的图片格式有误");
  100. }
  101. String original = file.getOriginalFilename().toLowerCase();
  102. if (original.indexOf("jpg") == -1 && original.indexOf("jpeg") == -1 && original.indexOf("png") == -1 && original.indexOf("gif") == -1 && original.indexOf("bmp") == -1) {
  103. return getFailureResult(201, "上传的图片格式有误");
  104. }
  105. // 保存文件
  106. try {
  107. String fileName = saveFile(file);
  108. String baseImage = settingService.getUploadBasePath();
  109. String filePath = baseImage + fileName;
  110. String url = filePath;
  111. // 上传阿里云oss
  112. String mode = env.getProperty("aliyun.oss.mode");
  113. if (mode.equals("1")) { // 检查是否开启上传
  114. String endpoint = env.getProperty("aliyun.oss.endpoint");
  115. String accessKeyId = env.getProperty("aliyun.oss.accessKeyId");
  116. String accessKeySecret = env.getProperty("aliyun.oss.accessKeySecret");
  117. String bucketName = env.getProperty("aliyun.oss.bucketName");
  118. String folder = env.getProperty("aliyun.oss.folder");
  119. String domain = env.getProperty("aliyun.oss.domain");
  120. OSS ossClient = AliyunOssUtil.getOSSClient(accessKeyId, accessKeySecret, endpoint);
  121. String pathRoot = env.getProperty("images.root");
  122. if (pathRoot == null || StringUtil.isEmpty(pathRoot)) {
  123. pathRoot = ResourceUtils.getURL("classpath:").getPath();
  124. }
  125. File ossFile = new File(pathRoot + fileName);
  126. fileName = AliyunOssUtil.upload(ossClient, ossFile, bucketName, folder);
  127. filePath = domain + fileName;
  128. url = filePath;
  129. }
  130. resultMap.put("status", "success");
  131. resultMap.put("domain", baseImage);
  132. resultMap.put("filePath", filePath);
  133. resultMap.put("fileName", fileName);
  134. resultMap.put("state", "SUCCESS");
  135. resultMap.put("original", file.getOriginalFilename());
  136. resultMap.put("size", file.getSize()+"");
  137. resultMap.put("title", fileName);
  138. resultMap.put("type", file.getContentType());
  139. resultMap.put("url", url);
  140. } catch (Exception e) {
  141. return getFailureResult(201, "上传失败,请检查上传配置及权限");
  142. }
  143. return getSuccessResult(resultMap);
  144. }
  145. public String saveFile(MultipartFile file) throws Exception {
  146. String fileName = file.getOriginalFilename();
  147. String imageName = fileName.substring(fileName.lastIndexOf("."));
  148. String pathRoot = env.getProperty("images.root");
  149. if (pathRoot == null || StringUtil.isEmpty(pathRoot)) {
  150. pathRoot = ResourceUtils.getURL("classpath:").getPath();
  151. }
  152. String uuid = UUID.randomUUID().toString().replaceAll("-", "");
  153. String baseImage = env.getProperty("images.path");
  154. String filePath = baseImage + DateUtil.formatDate(new Date(), "yyyyMMdd")+"/";
  155. String path = filePath + uuid + imageName;
  156. try {
  157. File tempFile = new File(pathRoot + path);
  158. if (!tempFile.getParentFile().exists()) {
  159. tempFile.getParentFile().mkdirs();
  160. }
  161. CommonUtil.saveMultipartFile(file, pathRoot + path);
  162. } catch (Exception e) {
  163. throw new Exception("上传失败,请检查目录是否可写");
  164. }
  165. return path;
  166. }
  167. }