Explorar o código

微信头像上传

yangfeng hai 1 ano
pai
achega
fbeef4ef44

+ 30 - 0
core/src/main/java/org/jeecg/common/util/MinioUtil.java

@@ -313,4 +313,34 @@ public class MinioUtil {
         return minioUrl + bucketName + "/" + relativePath;
     }
 
+    /**
+     * 上传文件到minio
+     *
+     * @param stream
+     * @return
+     */
+    public static String uploadFile(InputStream stream, String fileName) throws Exception {
+        try {
+            initMinio(minioUrl, minioName, minioPass);
+            if (minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
+                log.info("Bucket already exists.");
+            } else {
+                // 创建一个名为ota的存储桶
+                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
+                log.info("create a new bucket.");
+            }
+            StringBuilder objectName = new StringBuilder();
+            objectName.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/");
+            objectName.append(fileName);
+            PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName.toString())
+                    .bucket(bucketName)
+                    .contentType("application/octet-stream")
+                    .stream(stream, stream.available(), -1).build();
+            minioClient.putObject(objectArgs);
+            return objectName.toString();
+        } finally {
+            stream.close();
+        }
+    }
+
 }

+ 111 - 0
web/src/main/java/com/ynfy/app/api/v1/controller/ApiCommonController.java

@@ -2,18 +2,28 @@ package com.ynfy.app.api.v1.controller;
 
 import com.ynfy.app.api.v1.annoation.IgnoreAuth;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FileUtils;
+import org.jeecg.common.api.vo.Result;
 import org.jeecg.common.constant.CommonConstant;
 import org.jeecg.common.constant.SymbolConstant;
+import org.jeecg.common.exception.JeecgBootException;
+import org.jeecg.common.util.CommonUtils;
 import org.jeecg.common.util.MinioUtil;
+import org.jeecg.common.util.filter.FileTypeFilter;
 import org.jeecg.common.util.oConvertUtils;
 import org.jeecg.modules.system.entity.FileInfo;
 import org.jeecg.modules.system.service.IFileInfoService;
+import org.jeecg.modules.system.util.FileUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.util.AntPathMatcher;
+import org.springframework.util.FileCopyUtils;
 import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.MultipartHttpServletRequest;
 import org.springframework.web.servlet.HandlerMapping;
 
 import javax.servlet.http.HttpServletRequest;
@@ -44,6 +54,10 @@ public class ApiCommonController {
     private String uploadType;
 
 
+    @Value("${tmpPath}")
+    private String tmpPath;
+
+
     @Autowired
     private IFileInfoService fileInfoService;
 
@@ -180,4 +194,101 @@ public class ApiCommonController {
         return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
     }
 
+    /**
+     * 文件上传统一方法
+     *
+     * @param request
+     * @param response
+     * @return
+     */
+    @PostMapping(value = "/upload")
+    @IgnoreAuth
+    public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
+        String bizPath = request.getParameter("biz");
+        //LOWCOD-2580 sys/common/upload接口存在任意文件上传漏洞
+        if (oConvertUtils.isNotEmpty(bizPath)) {
+            if (bizPath.contains(SymbolConstant.SPOT_SINGLE_SLASH) || bizPath.contains(SymbolConstant.SPOT_DOUBLE_BACKSLASH)) {
+                throw new JeecgBootException("上传目录bizPath,格式非法!");
+            }
+        }
+        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
+        // 获取上传文件对象
+        MultipartFile file = multipartRequest.getFile("file");
+        if (oConvertUtils.isEmpty(bizPath)) {
+            if (CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)) {
+                //未指定目录,则用阿里云默认目录 upload
+                bizPath = "upload";
+            } else {
+                bizPath = "";
+            }
+        }
+        String savePath = null;
+        if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) {
+            FileTypeFilter.fileTypeFilter(file);
+            savePath = this.uploadLocal(file, bizPath);
+        } else {
+            savePath = CommonUtils.upload(file, bizPath, uploadType);
+        }
+
+        //是否计算视频时长
+        Boolean isVideoDuration = Boolean.parseBoolean(request.getParameter("isVideoDuration"));
+        Long videoDuration = null;
+        if (isVideoDuration && FileUtil.isVideo(file.getOriginalFilename())) {
+            File f = new File(tmpPath + File.separator + file.getOriginalFilename());
+            FileUtils.copyInputStreamToFile(file.getInputStream(), f);
+            videoDuration = CommonUtils.getVideoDuration(f);
+        }
+
+        //保存文件信息
+        fileInfoService.saveFile(savePath, file.getOriginalFilename(), videoDuration);
+        if (oConvertUtils.isNotEmpty(savePath)) {
+            return Result.ok(savePath);
+        } else {
+            return Result.error("上传失败!");
+        }
+    }
+
+    /**
+     * 本地文件上传
+     *
+     * @param mf      文件
+     * @param bizPath 自定义路径
+     * @return
+     */
+    private String uploadLocal(MultipartFile mf, String bizPath) {
+        try {
+            String ctxPath = uploadpath;
+            String fileName = null;
+            File file = new File(ctxPath + File.separator + bizPath + File.separator);
+            if (!file.exists()) {
+                // 创建文件根目录
+                file.mkdirs();
+            }
+            // 获取文件名
+            String orgName = mf.getOriginalFilename();
+            orgName = CommonUtils.getFileName(orgName);
+            if (orgName.indexOf(SymbolConstant.SPOT) != -1) {
+                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
+            } else {
+                fileName = orgName + "_" + System.currentTimeMillis();
+            }
+            String savePath = file.getPath() + File.separator + fileName;
+            File savefile = new File(savePath);
+            FileCopyUtils.copy(mf.getBytes(), savefile);
+            String dbpath = null;
+            if (oConvertUtils.isNotEmpty(bizPath)) {
+                dbpath = bizPath + File.separator + fileName;
+            } else {
+                dbpath = fileName;
+            }
+            if (dbpath.contains(SymbolConstant.DOUBLE_BACKSLASH)) {
+                dbpath = dbpath.replace(SymbolConstant.DOUBLE_BACKSLASH, SymbolConstant.SINGLE_SLASH);
+            }
+            return dbpath;
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+        }
+        return "";
+    }
+
 }

+ 135 - 0
web/src/main/java/com/ynfy/app/api/v1/util/HttpDownUtils.java

@@ -0,0 +1,135 @@
+package com.ynfy.app.api.v1.util;
+
+import org.jeecg.common.util.MinioUtil;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+
+public class HttpDownUtils {
+
+    /**
+     * 从网络Url中下载文件到本地磁盘
+     *
+     * @param urlStr
+     * @param fileName
+     * @param savePath
+     * @throws IOException
+     */
+    public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
+        URL url = new URL(urlStr);
+        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+        //设置超时间为3秒
+        conn.setConnectTimeout(30 * 1000);
+        conn.setReadTimeout(60 * 1000);
+        //得到输入流
+        InputStream inputStream = conn.getInputStream();
+        //获取自己数组
+        byte[] getData = readInputStream(inputStream);
+
+        //文件保存位置
+        File saveDir = new File(savePath);
+        if (!saveDir.exists()) {
+            saveDir.mkdir();
+        }
+        File file = new File(saveDir + File.separator + fileName);
+        FileOutputStream fos = new FileOutputStream(file);
+        fos.write(getData);
+        if (fos != null) {
+            fos.close();
+        }
+        if (inputStream != null) {
+            inputStream.close();
+        }
+    }
+
+
+    /**
+     * 从输入流中获取字节数组
+     *
+     * @param inputStream
+     * @return
+     * @throws IOException
+     */
+    public static byte[] readInputStream(InputStream inputStream) throws IOException {
+        byte[] buffer = new byte[1024];
+        int len = 0;
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        while ((len = inputStream.read(buffer)) != -1) {
+            bos.write(buffer, 0, len);
+        }
+        bos.close();
+        return bos.toByteArray();
+    }
+
+
+    /**
+     * 从网络url下载excel
+     *
+     * @param url
+     * @param fileName
+     * @param response
+     * @throws Exception
+     */
+    public void downloadExcelByUrl(String url, String fileName, HttpServletResponse response) throws Exception {
+        fileName = URLEncoder.encode(fileName, "UTF-8");
+        response.setContentType("application/vnd.ms-excel;charset=utf-8");
+        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
+        byte[] buff = new byte[1024];
+        BufferedInputStream bis = null;
+        OutputStream outputStream = null;
+        InputStream inputStream = null;
+        try {
+            URL httpUrl = new URL(url);
+            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
+            connection.setConnectTimeout(3000);
+            connection.setReadTimeout(5000);
+            outputStream = response.getOutputStream();
+            inputStream = connection.getInputStream();
+            bis = new BufferedInputStream(inputStream);
+            int len;
+            while ((len = bis.read(buff)) > 0) {
+                outputStream.write(buff, 0, len);
+                outputStream.flush();
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            if (bis != null) {
+                bis.close();
+            }
+            if (outputStream != null) {
+                outputStream.close();
+            }
+            if (inputStream != null) {
+                inputStream.close();
+            }
+        }
+    }
+
+
+    /**
+     * 从网络下载文件到本地,然后上传到minio
+     * @param url
+     * @param fileName
+     * @param tmpPath
+     * @return
+     */
+    public static String downFormUrlAndUpload(String url, String fileName, String tmpPath) {
+        try {
+            HttpDownUtils.downLoadFromUrl(url, fileName, tmpPath);
+            String destFilePath = tmpPath + File.separator + fileName;
+            File destFile = new File(destFilePath);
+            InputStream inputStream = new BufferedInputStream(new FileInputStream(destFile));
+            String objectName = MinioUtil.uploadFile(inputStream, fileName);
+            destFile.delete();
+            return objectName;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+}