BackendFileController.java 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 lombok.AllArgsConstructor;
  15. import org.springframework.security.access.prepost.PreAuthorize;
  16. import org.springframework.util.ResourceUtils;
  17. import org.springframework.web.bind.annotation.CrossOrigin;
  18. import org.springframework.web.bind.annotation.RequestMapping;
  19. import org.springframework.web.bind.annotation.RequestMethod;
  20. import org.springframework.web.bind.annotation.RestController;
  21. import org.springframework.web.multipart.MultipartFile;
  22. import org.springframework.web.multipart.MultipartHttpServletRequest;
  23. import org.slf4j.Logger;
  24. import org.slf4j.LoggerFactory;
  25. import org.springframework.core.env.Environment;
  26. import javax.servlet.http.HttpServletRequest;
  27. import javax.servlet.http.HttpServletResponse;
  28. import java.io.*;
  29. import java.net.URL;
  30. import java.util.Date;
  31. import java.util.HashMap;
  32. import java.util.Map;
  33. import java.util.UUID;
  34. /**
  35. * 文件上传管理控制类
  36. *
  37. * Created by FSQ
  38. * CopyRight https://www.fuint.cn
  39. */
  40. @Api(tags="管理端-文件上传相关接口")
  41. @RestController
  42. @AllArgsConstructor
  43. @RequestMapping(value = "/backendApi/file")
  44. public class BackendFileController extends BaseController {
  45. private static final Logger logger = LoggerFactory.getLogger(BackendFileController.class);
  46. /**
  47. * 环境变量
  48. * */
  49. private Environment env;
  50. /**
  51. * 系统设置服务接口
  52. * */
  53. private SettingService settingService;
  54. /**
  55. * 后台上传文件
  56. *
  57. * @param request
  58. * @throws
  59. */
  60. @ApiOperation(value = "后台上传文件")
  61. @RequestMapping(value = "/upload", method = RequestMethod.POST)
  62. @CrossOrigin
  63. public ResponseObject uploadFileLocal(HttpServletRequest request) {
  64. String token = request.getHeader("Access-Token");
  65. String action = request.getParameter("action") == null ? "" : request.getParameter("action");
  66. AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
  67. if (action.equals("config")) {
  68. Map<String, Object> outParams = new HashMap();
  69. outParams.put("imageActionName", "upload");
  70. outParams.put("fileActionName", "upload");
  71. outParams.put("fileFieldName", "file");
  72. outParams.put("imageFieldName", "file");
  73. outParams.put("fileUrlPrefix", "");
  74. outParams.put("imageUrlPrefix", "");
  75. return getSuccessResult(outParams);
  76. }
  77. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  78. String sourcePic = request.getParameter("sourcePic");// 页面图片元素的ID
  79. MultipartFile file = multipartRequest.getFile(sourcePic);
  80. if (file == null) {
  81. Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
  82. if (fileMap.size() > 0) {
  83. file = fileMap.get("file");
  84. }
  85. }
  86. Map<String, String> resultMap = new HashMap<>();
  87. String originalFilename = file.getOriginalFilename();
  88. if (StringUtil.isEmpty(originalFilename)) {
  89. return getFailureResult(201, "上传出错啦");
  90. }
  91. String maxSizeStr = env.getProperty("images.upload.maxSize");
  92. // 默认限制2M
  93. float maxSize = 2;
  94. try {
  95. maxSize = Float.parseFloat(maxSizeStr);
  96. } catch (NumberFormatException e) {
  97. logger.error("图片允许的大小设置不正确", e);
  98. }
  99. if (file.getSize() > (maxSize * 1024 * 1024)) {
  100. return getFailureResult(201, "上传的文件不能大于" + maxSize + "MB");
  101. }
  102. // 保存文件
  103. try {
  104. String fileName = saveFile(file);
  105. String baseImage = settingService.getUploadBasePath();
  106. String filePath = baseImage + fileName;
  107. String url = filePath;
  108. // 上传阿里云oss
  109. String mode = env.getProperty("aliyun.oss.mode");
  110. if (mode.equals("1")) { // 检查是否开启上传
  111. String endpoint = env.getProperty("aliyun.oss.endpoint");
  112. String accessKeyId = env.getProperty("aliyun.oss.accessKeyId");
  113. String accessKeySecret = env.getProperty("aliyun.oss.accessKeySecret");
  114. String bucketName = env.getProperty("aliyun.oss.bucketName");
  115. String folder = env.getProperty("aliyun.oss.folder");
  116. String domain = env.getProperty("aliyun.oss.domain");
  117. OSS ossClient = AliyunOssUtil.getOSSClient(accessKeyId, accessKeySecret, endpoint);
  118. String pathRoot = env.getProperty("images.root");
  119. if (pathRoot == null || StringUtil.isEmpty(pathRoot)) {
  120. pathRoot = ResourceUtils.getURL("classpath:").getPath();
  121. }
  122. File ossFile = new File(pathRoot + fileName);
  123. fileName = AliyunOssUtil.upload(ossClient, ossFile, bucketName, folder);
  124. filePath = domain + fileName;
  125. url = filePath;
  126. }
  127. resultMap.put("status", "success");
  128. resultMap.put("domain", baseImage);
  129. resultMap.put("filePath", filePath);
  130. resultMap.put("fileName", fileName);
  131. resultMap.put("state", "SUCCESS");
  132. resultMap.put("original", file.getOriginalFilename());
  133. resultMap.put("size", file.getSize()+"");
  134. resultMap.put("title", fileName);
  135. resultMap.put("type", file.getContentType());
  136. resultMap.put("url", url);
  137. String ip = CommonUtil.getIPFromHttpRequest(request);
  138. logger.info("用户ip:{},上传文件url:{},account:{}", ip, url, accountInfo.getAccountName());
  139. } catch (Exception e) {
  140. return getFailureResult(201, "上传失败,请检查上传配置及权限");
  141. }
  142. return getSuccessResult(resultMap);
  143. }
  144. /**
  145. * 下载文件
  146. *
  147. * @return
  148. */
  149. @ApiOperation(value = "下载文件")
  150. @RequestMapping(value = "/download", method = RequestMethod.GET)
  151. @CrossOrigin
  152. public void download(HttpServletRequest request, HttpServletResponse response) {
  153. String token = request.getParameter("token");
  154. AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
  155. try {
  156. URL resourceUrl = getClass().getClassLoader().getResource("GoodsTemplate.xlsx");
  157. String path = resourceUrl.getPath();
  158. File file = new File(path);
  159. String filename = file.getName();
  160. InputStream fis = new BufferedInputStream(new FileInputStream(path));
  161. byte[] buffer = new byte[fis.available()];
  162. fis.read(buffer);
  163. fis.close();
  164. response.reset();
  165. response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
  166. response.addHeader("Content-Length", "" + file.length());
  167. OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
  168. response.setContentType("application/octet-stream");
  169. toClient.write(buffer);
  170. toClient.flush();
  171. toClient.close();
  172. } catch (IOException ex) {
  173. ex.printStackTrace();
  174. logger.error("下载文件出错:account = {}", accountInfo.getAccountName());
  175. }
  176. }
  177. public String saveFile(MultipartFile file) throws Exception {
  178. String fileName = file.getOriginalFilename();
  179. String imageName = fileName.substring(fileName.lastIndexOf("."));
  180. String pathRoot = env.getProperty("images.root");
  181. if (pathRoot == null || StringUtil.isEmpty(pathRoot)) {
  182. pathRoot = ResourceUtils.getURL("classpath:").getPath();
  183. }
  184. String uuid = UUID.randomUUID().toString().replaceAll("-", "");
  185. String baseImage = env.getProperty("images.path");
  186. String filePath = baseImage + DateUtil.formatDate(new Date(), "yyyyMMdd")+"/";
  187. String path = filePath + uuid + imageName;
  188. try {
  189. File tempFile = new File(pathRoot + path);
  190. if (!tempFile.getParentFile().exists()) {
  191. tempFile.getParentFile().mkdirs();
  192. }
  193. CommonUtil.saveMultipartFile(file, pathRoot + path);
  194. } catch (Exception e) {
  195. throw new Exception("上传失败,请检查目录是否可写");
  196. }
  197. return path;
  198. }
  199. }