当前位置:   article > 正文

springboot下阿里云OSS文件上传_url "ossservice/osstype" does not contain "{osstyp

url "ossservice/osstype" does not contain "{osstype}". (parameter #1)
  1. package com.admin.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.aliyun.oss.OSSClient;
  4. import com.aliyun.oss.common.utils.BinaryUtil;
  5. import com.aliyun.oss.model.*;
  6. import com.admin.config.BaseController;
  7. import com.appapi.common.FileUploadApiController;
  8. import com.appapi.util.GeneratorUtil;
  9. import org.apache.commons.io.FilenameUtils;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import org.springframework.beans.factory.InitializingBean;
  13. import org.springframework.stereotype.Controller;
  14. import org.springframework.web.bind.annotation.*;
  15. import org.springframework.web.multipart.MultipartFile;
  16. import javax.servlet.ServletException;
  17. import javax.servlet.http.HttpServletRequest;
  18. import javax.servlet.http.HttpServletResponse;
  19. import java.io.IOException;
  20. import java.sql.Date;
  21. import java.util.HashMap;
  22. import java.util.Map;
  23. @Controller
  24. @RequestMapping("/common")
  25. public class FileUploadController extends BaseController implements InitializingBean {
  26. private static final Logger logger = LoggerFactory.getLogger(FileUploadApiController.class);
  27. //密匙keyId 可以在阿里云获取到
  28. public static String accessId = "你的阿里云accessId ";
  29. //密匙keySecret 可以在阿里云获取到
  30. public static String accessKey = "你的阿里云accessKey ";
  31. //你的oss所在域,要加http:// 不明白可以对照你的文件引用地址
  32. public static String endpoint = "oss-cn-shenzhen.aliyuncs.com";
  33. //你的bucketName 名称 即是你的OSS对象名称 不明白查oss开发文档专业术语
  34. public static String bucket = "ygyxj";
  35. private static String callbackUrl="";
  36. private static String dir="文件保存地址/";
  37. private static String baseUrl="https://ygyxj.oss-cn-shenzhen.aliyuncs.com/";
  38. /*@Autowired
  39. private OSS ossClient2;*/
  40. // @Autowired(required=true)
  41. private static OSSClient ossClient = new OSSClient(endpoint, accessId, accessKey);
  42. private String host;
  43. // @Autowired
  44. // private StringRedisTemplate stringRedisTemplate;
  45. @Override
  46. public void afterPropertiesSet() throws Exception {
  47. host = "http://" + bucket + "." + endpoint;
  48. }
  49. /**
  50. * 前台签名直传, 由服务器签名,用户可直接上传图片
  51. * 这种只支持 Aliyun(因为我编码查看文档时,只有阿里云做了这个设计) 优点是 上传不需要占用应用服务器带宽。 目前前端是使用的这个。
  52. * 若需要更改,请自行修改前端上传逻辑
  53. * @param request
  54. * @param response
  55. */
  56. @RequestMapping(method = RequestMethod.GET)
  57. public void upload(HttpServletRequest request, HttpServletResponse response) {
  58. try {
  59. long expireTime = 30;
  60. long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
  61. Date expiration = new Date(expireEndTime);
  62. PolicyConditions policyConds = new PolicyConditions();
  63. policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
  64. policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
  65. String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
  66. byte[] binaryData = postPolicy.getBytes("utf-8");
  67. String encodedPolicy = BinaryUtil.toBase64String(binaryData);
  68. String postSignature = ossClient.calculatePostSignature(postPolicy);
  69. JSONObject respJsonObj = new JSONObject();
  70. respJsonObj.put("accessid", accessId);
  71. respJsonObj.put("policy", encodedPolicy);
  72. respJsonObj.put("signature", postSignature);
  73. respJsonObj.put("dir", dir);
  74. respJsonObj.put("host", host);
  75. respJsonObj.put("expire", String.valueOf(expireEndTime / 1000));
  76. // respMap.put("expire", formatISO8601Date(expiration));
  77. JSONObject jasonCallback = new JSONObject();
  78. jasonCallback.put("callbackUrl", callbackUrl);
  79. jasonCallback.put("callbackBody",
  80. "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
  81. jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
  82. String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
  83. respJsonObj.put("callback", base64CallbackBody);
  84. // System.out.println(ja1.toString());
  85. response.setHeader("Access-Control-Allow-Origin", "*");
  86. response.setHeader("Access-Control-Allow-Methods", "GET, POST");
  87. respJsonObj.put("code", 200);
  88. respJsonObj.put("baseUrl", baseUrl);
  89. response(request, response, respJsonObj.toJSONString());
  90. } catch (Exception e) {
  91. e.printStackTrace();
  92. logger.error("[上传签名] 异常", e);
  93. }
  94. }
  95. /**
  96. * 后台通过服务器间接传文件
  97. * @param file
  98. * @return
  99. * @throws IOException
  100. */
  101. @PostMapping("/upload")
  102. public @ResponseBody Map<String, Object> create(@RequestParam("file") MultipartFile file) throws IOException {
  103. ObjectMetadata objectMetadata = new ObjectMetadata();
  104. String fileName = file.getOriginalFilename();
  105. String uuid = GeneratorUtil.genFileName();
  106. objectMetadata.setContentLength(file.getSize());
  107. objectMetadata.setContentType(file.getContentType());
  108. // objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
  109. String ext = FilenameUtils.getExtension(file.getOriginalFilename());
  110. PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, "park/" + uuid+"."+ext, file.getInputStream(), objectMetadata);
  111. PutObjectResult re = ossClient.putObject(putObjectRequest);
  112. Map<String, Object> data = new HashMap<>();
  113. data.put("url", baseUrl + "park/" + uuid +"."+ext);
  114. data.put("code", 200);
  115. data.put("msg", "成功");
  116. data.put("size", file.getSize());
  117. return data;
  118. // return baseUrl + "park/" + uuid +"."+ext;
  119. // return "服务器错误";
  120. }
  121. /**
  122. * Description: 判断OSS服务文件上传时文件的contentType
  123. *
  124. * @param FilenameExtension 文件后缀
  125. * @return String
  126. */
  127. public static String getcontentType(String FilenameExtension) {
  128. if (FilenameExtension.equalsIgnoreCase(".bmp")) {
  129. return "image/bmp";
  130. }
  131. if (FilenameExtension.equalsIgnoreCase(".gif")) {
  132. return "image/gif";
  133. }
  134. if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
  135. FilenameExtension.equalsIgnoreCase(".jpg") ||
  136. FilenameExtension.equalsIgnoreCase(".png")) {
  137. return "image/jpeg";
  138. }
  139. if (FilenameExtension.equalsIgnoreCase(".html")) {
  140. return "text/html";
  141. }
  142. if (FilenameExtension.equalsIgnoreCase(".txt")) {
  143. return "text/plain";
  144. }
  145. if (FilenameExtension.equalsIgnoreCase(".vsd")) {
  146. return "application/vnd.visio";
  147. }
  148. if (FilenameExtension.equalsIgnoreCase(".pptx") ||
  149. FilenameExtension.equalsIgnoreCase(".ppt")) {
  150. return "application/vnd.ms-powerpoint";
  151. }
  152. if (FilenameExtension.equalsIgnoreCase(".docx") ||
  153. FilenameExtension.equalsIgnoreCase(".doc")) {
  154. return "application/msword";
  155. }
  156. if (FilenameExtension.equalsIgnoreCase(".xml")) {
  157. return "text/xml";
  158. }
  159. return "image/jpeg";
  160. }
  161. /**
  162. * Post请求
  163. */
  164. @RequestMapping(method = RequestMethod.POST)
  165. public void doPost(HttpServletRequest request, HttpServletResponse response)
  166. throws ServletException, IOException {
  167. Map<String, String[]> parameterMap = request.getParameterMap();
  168. JSONObject responseJson = new JSONObject();
  169. responseJson.put("code", 200);
  170. for (String key : parameterMap.keySet()) {
  171. responseJson.put(key, parameterMap.get(key)[0]);
  172. }
  173. response(request, response, responseJson.toJSONString(), HttpServletResponse.SC_OK);
  174. }
  175. /**
  176. * 服务器响应结果
  177. *
  178. * @param request
  179. * @param response
  180. * @param results
  181. * @param status
  182. * @throws IOException
  183. */
  184. private void response(HttpServletRequest request, HttpServletResponse response, String results, int status)
  185. throws IOException {
  186. String callbackFunName = request.getParameter("callback");
  187. response.addHeader("Content-Length", String.valueOf(results.length()));
  188. if (callbackFunName == null || callbackFunName.equalsIgnoreCase(""))
  189. response.getWriter().println(results);
  190. else
  191. response.getWriter().println(callbackFunName + "( " + results + " )");
  192. response.setStatus(status);
  193. response.flushBuffer();
  194. }
  195. /**
  196. * 服务器响应结果
  197. */
  198. private void response(HttpServletRequest request, HttpServletResponse response, String results) throws IOException {
  199. String callbackFunName = request.getParameter("callback");
  200. if (callbackFunName == null || callbackFunName.equalsIgnoreCase(""))
  201. response.getWriter().println(results);
  202. else
  203. response.getWriter().println(callbackFunName + "( " + results + " )");
  204. response.setStatus(HttpServletResponse.SC_OK);
  205. response.flushBuffer();
  206. }
  207. //删除文件
  208. public void deleteFile(@RequestParam("fileName")String fileName){
  209. OSSClient ossClientDelete = new OSSClient(endpoint, accessId, accessKey);
  210. String file = fileName.replace("https://ygyxj.oss-cn-shenzhen.aliyuncs.com/","");
  211. ossClientDelete.deleteObject(bucket, file);
  212. logger.info(fileName+"删除成功");
  213. ossClientDelete.shutdown();
  214. }
  215. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/346801?site
推荐阅读
相关标签
  

闽ICP备14008679号