Parcourir la source

移动端新增文件上传

赵冬冬 il y a 4 ans
Parent
commit
d41b505637

+ 6 - 0
forest-portal/portal-server/pom.xml

@@ -88,6 +88,12 @@
             <version>3.1.0</version>
         </dependency>
 
+        <dependency>
+            <groupId>com.qiniu</groupId>
+            <artifactId>qiniu-java-sdk</artifactId>
+            <version>7.2.28</version>
+        </dependency>
+
         <!--微信公众号开发登录-->
         <dependency>
             <groupId>com.github.binarywang</groupId>

+ 0 - 1
forest-portal/portal-server/src/main/java/com/hwrj/cloud/portal/config/exception/GlobalExceptionHandler.java

@@ -1,7 +1,6 @@
 package com.hwrj.cloud.portal.config.exception;
 
 import com.hwrj.cloud.common.api.CommonResult;
-import com.hwrj.cloud.common.api.IErrorCode;
 import org.springframework.web.bind.annotation.ControllerAdvice;
 import org.springframework.web.bind.annotation.ExceptionHandler;
 import org.springframework.web.bind.annotation.ResponseBody;

+ 36 - 0
forest-portal/portal-server/src/main/java/com/hwrj/cloud/portal/controller/FileUploadController.java

@@ -0,0 +1,36 @@
+package com.hwrj.cloud.portal.controller;
+
+
+import com.hwrj.cloud.common.api.CommonResult;
+import com.hwrj.cloud.portal.util.OrderNo;
+import com.hwrj.cloud.portal.util.UploadFileUtil;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+@Api(tags = "FileUploadController",description = "图片上传接口")
+@RestController
+@RequestMapping("/upload")
+public class FileUploadController {
+
+    @Autowired
+    private UploadFileUtil uploadFileUtil;
+
+    @ApiOperation("上传接口")
+    @PostMapping("/fileImg")
+    public CommonResult uploadFile(@RequestParam(value = "file") MultipartFile file,String type){
+        type =1+"";
+        if ((!"123456".contains(type))||type.length()>1){
+            return CommonResult.failed("上传失败");
+        }
+        String s = uploadFileUtil.uploadQiNiuFiles(file, "0/" + type + "/" + OrderNo.NextOrderNo());
+        return CommonResult.success(s);
+    }
+
+
+}

+ 47 - 0
forest-portal/portal-server/src/main/java/com/hwrj/cloud/portal/util/OrderNo.java

@@ -0,0 +1,47 @@
+package com.hwrj.cloud.portal.util;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+public class OrderNo {
+    private static int sn = 0;
+
+    public static String NextOrderNo(){
+        if(sn == 999999999)
+            sn = 0;
+        else
+            sn++;
+        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
+        return df.format(new Date()) + padRight(String.valueOf(sn),9, '0');
+    }
+    public static String padLeft(String src, int len, char ch) {
+        int diff = len - src.length();
+        if (diff <= 0) {
+            return src;
+        }
+
+        char[] charr = new char[len];
+        System.arraycopy(src.toCharArray(), 0, charr, 0, src.length());
+        for (int i = src.length(); i < len; i++) {
+            charr[i] = ch;
+        }
+        return new String(charr);
+    }
+    public static String padRight(String src, int len, char ch) {
+        int diff = len - src.length();
+        if (diff <= 0) {
+            return src;
+        }
+
+        char[] charr = new char[len];
+        System.arraycopy(src.toCharArray(), 0, charr, diff, src.length());
+        for (int i = 0; i < diff; i++) {
+            charr[i] = ch;
+        }
+        return new String(charr);
+    }
+    // 防止创建类的实例
+    private OrderNo(){}
+
+}

+ 103 - 0
forest-portal/portal-server/src/main/java/com/hwrj/cloud/portal/util/UploadFileUtil.java

@@ -0,0 +1,103 @@
+package com.hwrj.cloud.portal.util;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.google.gson.Gson;
+import com.hwrj.cloud.common.exception.GlobalException;
+import com.qiniu.common.QiniuException;
+import com.qiniu.common.Zone;
+import com.qiniu.http.Response;
+import com.qiniu.storage.Configuration;
+import com.qiniu.storage.UploadManager;
+import com.qiniu.storage.model.DefaultPutRet;
+import com.qiniu.util.Auth;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+
+@Slf4j
+@Component
+public class UploadFileUtil {
+    @Value("${qiniu.accessKey}")
+    private String accessKey;
+
+    @Value("${qiniu.secretKey}")
+    private String secretKey;
+
+    @Value("${qiniu.bucket}")
+    private String bucket;
+
+    @Value("${qiniu.path}")
+    private String url;
+
+    public String uploadQiNiuFiles(@RequestParam("file") MultipartFile file, String path){
+        String contentType = file.getContentType();
+        String[] split = null;
+        try{
+            split = contentType.split("/");
+        }catch (Exception e){
+            throw new GlobalException("获取文件后缀出错!=======>"+split);
+        }
+        path = path+"."+split[split.length-1];
+        //构建一个带指定对象的配置类
+        Configuration cof = new Configuration(Zone.autoZone());
+        UploadManager uploadManager = new UploadManager(cof);
+        String uploadToken = getUploadToken();
+        DefaultPutRet defaultPutRet = null;
+        try{
+            Response response = uploadManager.put(file.getInputStream(), path, uploadToken, null, null);
+            defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
+            log.info(JSONObject.toJSONString(defaultPutRet));
+            return url+path;
+        }catch (QiniuException ex){
+            Response r = ex.response;
+            log.error(""+r.toString());
+            try {
+                log.error(r.bodyString());
+            } catch (QiniuException ex2) {
+                //ignore
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+           return null;
+        }
+        return null;
+    }
+    /**
+     * @MethodName getUploadToken
+     * @Param []
+     * @Return java.lang.String
+     * @Author qiubo
+     * @Date 2020/5/11
+     * @Description 获取七牛云上传图片的token
+     */
+    public String getUploadToken(){
+        Auth auth = Auth.create(accessKey, secretKey);
+        return auth.uploadToken(bucket);
+    }
+
+    public String uploadLocalFile(String path,String url){
+        Configuration cof = new Configuration(Zone.autoZone());
+        UploadManager uploadManager = new UploadManager(cof);
+        try {
+            Response response = uploadManager.put(path, url, getUploadToken());
+            //解析上传成功的结果
+            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
+            System.out.println(putRet.key);
+            return putRet.key;
+        } catch (QiniuException ex) {
+            Response r = ex.response;
+            System.err.println(r.toString());
+            try {
+                System.err.println(r.bodyString());
+            } catch (QiniuException ex2) {
+                //ignore
+            }
+        }
+        return null;
+    }
+}