diff --git a/pom.xml b/pom.xml index 481bf0d29..b7d988b79 100644 --- a/pom.xml +++ b/pom.xml @@ -207,7 +207,7 @@ <module>ruoyi-common</module> <module>ruoyi-yunbookmark</module> <module>ruoyi-note</module> - + <module>yunpan-baidu</module> </modules> <packaging>pom</packaging> diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index 32a95d44d..86e2edbd7 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -89,6 +89,11 @@ <artifactId>spring-boot-starter-test</artifactId> </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpmime</artifactId> + <version>4.5.6</version> + </dependency> </dependencies> diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/BaiDuWangPan.java b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/BaiDuWangPan.java new file mode 100644 index 000000000..458fee047 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/BaiDuWangPan.java @@ -0,0 +1,143 @@ +package com.ruoyi.web.test.controller; + + +import cn.hutool.http.HttpUtil; +import com.alibaba.fastjson.JSONObject; +import com.ruoyi.baidu.servise.BaiduWangPanServise; +import com.ruoyi.common.constant.BaiduUrl; +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.io.*; +import java.util.HashMap; + +/** + * @Auther: Wang + * @Date: 2021/07/24 22:37 + * 功能描述: + * //教程 + * //https://blog.csdn.net/admans/article/details/80653490 + */ +public class BaiDuWangPan extends BaseSpringBootTest{ + + @Autowired + private BaiduWangPanServise baiduWangPanServise; + + private static String access_token = "123.5f2c72c8c2106a3baa177de77331b1d1.YnelNhviWQotgsooAt63iCRbaqZrjEP0Qgj3nIx.jMfNkQ"; + + + // 获取用户信息 + @Test + public void getUser() { + String result = baiduWangPanServise.getUserInfo(access_token); + JSONObject object = JSONObject.parseObject(result); + System.out.println("result:" + result); + System.out.println("baidu_name:" + object.get("baidu_name")); + System.out.println("netdisk_name:" + object.get("netdisk_name")); + } + + // 获取容量 + @Test + public void getCapacity() { + String result = baiduWangPanServise.getCapacity(access_token); + System.out.println("result:" + result); + } + + + // 上传文件 + @Test + public void addFile() { + + //预上传、分片上传、创建文件 + String md5 = ""; + try { + md5 = DigestUtils.md5Hex(new FileInputStream(new File("D:\\Wang\\22.txt"))); + } catch (IOException e) { + e.printStackTrace(); + } + //预上传 获取ID + + HashMap<String, Object> paramMap = new HashMap<>(); + paramMap.put("access_token", access_token); + paramMap.put("path", "/apps/藏趣云/22.txt"); + paramMap.put("size", "1");//文件或目录的大小,单位B + paramMap.put("isdir", "0");//是否目录,0 文件、1 目录 + paramMap.put("block_list", "[\"" + md5 + "\"]"); + paramMap.put("autoinit", 1); + String result = HttpUtil.post("https://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token" + access_token, paramMap); + System.out.println("result:" + result); + + JSONObject object = JSONObject.parseObject(result); + String uploadid = object.getString("uploadid"); + System.out.println("uploadid:" + uploadid); + + + //上传文件 + HashMap<String, Object> paramMap1 = new HashMap<>(); +// paramMap1.put("file", ReadFileToCharArray("D:\\Wang\\22.txt")); + paramMap1.put("file", new File("D:\\Wang\\22.txt")); + + System.out.println("file:" + paramMap1.get("file").toString()); + +// String result2 = HttpUtil.post("https://d.pcs.baidu.com/rest/2.0/pcs/superfile2?access_token=" + access_token + "&method=upload&type=tmpfile&path=%2Fapps%2F%E8%97%8F%E8%B6%A3%E4%BA%91%2F22.txt&partseq=0&uploadid=" + uploadid, paramMap1); +// System.out.println("result2:" + result2); + String url = Constant.SLICING_UPLOAD_FILE_URL + "?method=upload" + + "&access_token=" + Constant.ATOKEN + + "&type=tmpfile&partseq=0" + + "&path=" + Constant.APP_PATH + "22.txt" + + "&uploadid=" + uploadid; + String result2 = FileUtilsBaidu.sendFile(url,new File("D:\\Wang\\22.txt")); + System.out.println("result2:" + result2); + + //创建文件 + HashMap<String, Object> paramMap3 = new HashMap<>(); +// paramMap1.put("file", ReadFileToCharArray("D:\\Wang\\22.txt")); + paramMap3.put("path", "/apps/藏趣云/22.txt"); + paramMap3.put("size", 6); + paramMap3.put("isdir", 0); + + + String result3 = HttpUtil.post("https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=" + access_token, paramMap3); + System.out.println("result3:" + result3); + + + } + + + + + + + + + + + + + + + + + + //将文件转换成char[]数组 + public static char[] ReadFileToCharArray(String filePath) throws IOException { + StringBuilder fileData = new StringBuilder(1000); + BufferedReader reader = new BufferedReader(new FileReader(filePath)); + + char[] buf = new char[10]; + int numRead = 0; + while ((numRead = reader.read(buf)) != -1) { + System.out.println(numRead); + String readData = String.valueOf(buf, 0, numRead); + fileData.append(readData); + buf = new char[1024]; + } + + reader.close(); + + return fileData.toString().toCharArray(); + } + + +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/Constant.java b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/Constant.java new file mode 100644 index 000000000..beafd389d --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/Constant.java @@ -0,0 +1,55 @@ +package com.ruoyi.web.test.controller; + +/** + * @Auther: Wang + * @Date: 2021/07/25 02:03 + * 功能描述: + */ +public interface Constant { + String APP_ID="24066444"; + String APP_NAME="藏趣云"; + String APP_KEY="7NpRdcorSxoqxIKAkzLXuOhVr8NQekA9"; + String SECRET_KEY="RfvvGbkN95CuXlaoZVzzsvGiz9Her6qq"; + String SING_key="dBpomXW%duC2L8l6MW3yTpaXhX=-8oj0"; + String APP_PATH="/apps/"+APP_NAME+"/"; + +// https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=7NpRdcorSxoqxIKAkzLXuOhVr8NQekA9&redirect_uri=https://www.baidu.com/&scope=basic,netdisk&display=tv&qrcode=1&force_login=1 + // https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code=0a291eb3fd3ed6ccc74cc46bc5540191&client_id=7NpRdcorSxoqxIKAkzLXuOhVr8NQekA9&client_secret=RfvvGbkN95CuXlaoZVzzsvGiz9Her6qq&redirect_uri=oob + //单位mb + // 普通用户单个分片大小固定为4MB(文件大小如果小于4MB,无需切片,直接上传即可),单文件总大小上限为4G。 + //普通会员用户单个分片大小上限为16MB,单文件总大小上限为10G。 + //超级会员用户单个分片大小上限为32MB,单文件总大小上限为20G。 + Integer UNIT=4; + + + //获取授权码,需要扫码登陆 + String GET_CODE_URL="https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id="+APP_KEY+"&redirect_uri=oob&scope=basic,netdisk&display=tv&qrcode=1&force_login=1"; + + //获取到的授权码 + String CODE="0a291eb3fd3ed6ccc74cc46bc5540191"; + + //根据授权码换取token + String GET_TOKEN_BY_CODE="https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code="+CODE+"&client_id="+APP_KEY+"&client_secret="+SECRET_KEY+"&redirect_uri=oob"; + + //获取到的TOKEN + String RTOKEN="122.fec5f9d6dd1644c2c57c89cc510f7ec8.YBMpVZwjo9y5kSMFnVmSMJL9dj25T5X02gjLwV8.1J2sEw"; + String ATOKEN="121.d8ab3687bd67e9b245b6a10f7af7afc3.YCQGBie5JO6U7nCl-ZLVC3pX-sTUFIgnV6hH1Rw.3zI4rQ"; + + + //操作文件 copy, mover, rename, delete + String FILE_MANAGER_URL=" https://pan.baidu.com/rest/2.0/xpan/file"; + + //预上传 + String GET_READY_FILE_URL="https://pan.baidu.com/rest/2.0/xpan/file"; + + //分片上传 + String SLICING_UPLOAD_FILE_URL="https://d.pcs.baidu.com/rest/2.0/pcs/superfile2"; + + //下载文件 + String DOWN_LOUE_URL="https://pan.baidu.com/rest/2.0/xpan/multimedia"; + + //文件搜索 + String FILE_SEARCH="https://pan.baidu.com/rest/2.0/xpan/file?method=search"; + + +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/FileSizeUtil.java b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/FileSizeUtil.java new file mode 100644 index 000000000..39a2cc6ba --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/FileSizeUtil.java @@ -0,0 +1,183 @@ +package com.ruoyi.web.test.controller; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.text.DecimalFormat; + +/** + * @Auther: Wang + * @Date: 2021/07/25 17:51 + * 功能描述: + */ +public class FileSizeUtil { + private static final String TAG=FileSizeUtil.class.getSimpleName(); + + public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值 + public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值 + public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值 + public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值 + + /** + * @param @param imgPath + * @param @return 根据图片地址返回图片大小kb或者 Mb + * @return String + * @throws + * @Title: pathSize + * @add (default no) + */ + public static String pathSize(String imgPath) { + File file = new File(imgPath); + FileInputStream fis; + int fileLen = 0; + try { + fis = new FileInputStream(file); + fileLen = fis.available(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return String.valueOf(fileLen); + } + + /** + * 获取文件指定文件的指定单位的大小 + * + * @param filePath 文件路径 + * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB + * @return double值的大小 + */ + public static double getFileOrFilesSize(String filePath, int sizeType) { + File file = new File(filePath); + long blockSize = 0; + try { + if (file.isDirectory()) { + blockSize = getFileSizes(file); + } else { + blockSize = getFileSize(file); + } + } catch (Exception e) { + e.printStackTrace(); +// LogUtil.E(TAG,"获取文件大小失败!"); + } + return FormetFileSize(blockSize, sizeType); + } + + /** + * 调用此方法自动计算指定文件或指定文件夹的大小 + * + * @param filePath 文件路径 + * @return 计算好的带B、KB、MB、GB的字符串 + */ + public static String getAutoFileOrFilesSize(String filePath) { + File file = new File(filePath); + long blockSize = 0; + try { + if (file.isDirectory()) { + blockSize = getFileSizes(file); + } else { + blockSize = getFileSize(file); + } + } catch (Exception e) { + e.printStackTrace(); +// LogUtil.E(TAG,"获取文件大小失败!"); + } + return FormetFileSize(blockSize); + } + + /** + * 获取指定文件大小 + * + * @param file + * @return + * @throws Exception + */ + private static long getFileSize(File file) throws Exception { + long size = 0; + if (file.exists()) { + FileInputStream fis = null; + fis = new FileInputStream(file); + size = fis.available(); + } else { + file.createNewFile(); +// LogUtil.E(TAG,"获取文件大小不存在!"); + } + return size; + } + + /** + * 获取指定文件夹 + * + * @param f + * @return + * @throws Exception + */ + private static long getFileSizes(File f) throws Exception { + long size = 0; + File flist[] = f.listFiles(); + for (int i = 0; i < flist.length; i++) { + if (flist[i].isDirectory()) { + size = size + getFileSizes(flist[i]); + } else { + size = size + getFileSize(flist[i]); + } + } + return size; + } + + /** + * 转换文件大小 + * + * @param fileS + * @return + */ + private static String FormetFileSize(long fileS) { + DecimalFormat df = new DecimalFormat("#.00"); + String fileSizeString = ""; + String wrongSize = "0B"; + if (fileS == 0) { + return wrongSize; + } + if (fileS < 1024) { + fileSizeString = df.format((double) fileS) + "B"; + } else if (fileS < 1048576) { + fileSizeString = df.format((double) fileS / 1024) + "KB"; + } else if (fileS < 1073741824) { + fileSizeString = df.format((double) fileS / 1048576) + "MB"; + } else { + fileSizeString = df.format((double) fileS / 1073741824) + "GB"; + } + return fileSizeString; + } + + /** + * 转换文件大小,指定转换的类型 + * + * @param fileS + * @param sizeType + * @return + */ + private static double FormetFileSize(long fileS, int sizeType) { + DecimalFormat df = new DecimalFormat("#.00"); + double fileSizeLong = 0; + switch (sizeType) { + case SIZETYPE_B: + fileSizeLong = Double.valueOf(df.format((double) fileS)); + break; + case SIZETYPE_KB: + fileSizeLong = Double.valueOf(df.format((double) fileS / 1024)); + break; + case SIZETYPE_MB: + fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576)); + break; + case SIZETYPE_GB: + fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824)); + break; + default: + break; + } + return fileSizeLong; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/FileUtilsBaidu.java b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/FileUtilsBaidu.java new file mode 100644 index 000000000..024400287 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/FileUtilsBaidu.java @@ -0,0 +1,570 @@ +package com.ruoyi.web.test.controller; + +import cn.hutool.core.io.FileUtil; +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import cn.hutool.http.HttpUtil; +import cn.hutool.json.JSONArray; +import cn.hutool.json.JSONObject; +import cn.hutool.log.Log; +import cn.hutool.log.LogFactory; +import lombok.SneakyThrows; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.apache.velocity.runtime.directive.Foreach; + +import java.io.*; +import java.math.BigInteger; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; + +/** + * @Auther: Wang + * @Date: 2021/07/25 02:02 + * 功能描述: + */ +public class FileUtilsBaidu { + + private static final Log log = LogFactory.get(); + + + public static void main(String[] args) { + //不能有空格 + String filePath = "D:\\data\\ces\\"; + String fileName = "day4_MySQL性能优化总结.zip"; + System.out.println(save(filePath, fileName)); + } + + /** + * @Description: TODO 保存文件 + * @param: filePath 文件路径 + * @param: fileName 文件名称 + * return 文件下载地址 + */ + @SneakyThrows + private static String save(String filePath, String fileName) { + //本地文件地址 + String absoluteFilePath = filePath + fileName; + //云端文件地址 + String cloudPath = Constant.APP_PATH + fileName; + + //文件分片并获取md5值 + File file = new File(absoluteFilePath); + File[] separate = separate(absoluteFilePath, Constant.UNIT); + StringBuffer md5s = new StringBuffer(); + if (separate.length == 1) { + md5s.append(getMD5(separate[0])); +// md5s.append(DigestUtils.md5Hex(new FileInputStream(separate[0]))); + } + if (separate.length > 1) { + for (int i = 0; i < separate.length; i++) { + md5s.append(getMD5(separate[i]) + "\",\""); +// md5s.append(DigestUtils.md5Hex(new FileInputStream(separate[i])) + "\",\""); + log.info("正在分片,{}{}", separate[i].toString(), i); + } + String s = md5s.toString(); + md5s = new StringBuffer(s.substring(0, md5s.length() - 3)); + } + + Long fileMax = file.length(); + + //预上传 + String precreate = precreate(cloudPath,fileMax, 0, md5s.toString()); + log.info("预上传{} iploadid是 {} md5{}", precreate,(String) new JSONObject(precreate).get("uploadid"),md5s.toString()); + + //分片上传 + String upload = upload(cloudPath, (String) new JSONObject(precreate).get("uploadid"), separate); + log.info("分片上传{}", upload); + log.info(" >>>>>>>>>>>>>>>>>>>>>>>>>>"); + + Thread.sleep(3000); + //创建文件 + + log.info("创建文件 fileName{} 文件大小{} md5:{} ID:{}", fileName,FileSizeUtil.pathSize(absoluteFilePath),md5s.toString(),(String) new JSONObject(precreate).get("uploadid")); + String create = create(fileName, fileMax, 0, md5s.toString(),(String) new JSONObject(precreate).get("uploadid")); + log.info("创建文件{}", create); + + //获取下载地址 + String downUrl = getDownUrl(fileName); + log.info("获取下载地址{}", downUrl); + + return downUrl; + } + + + /** + * @Description: TODO 获取下载地址 + * @param: fileName 文件名 + */ + private static String getDownUrl(String fileName) { + String fileSearch = HttpUtil.get(Constant.FILE_SEARCH + "&access_token=" + Constant.ATOKEN + "&key=" + fileName); + JSONObject jsonObject = new JSONObject(fileSearch); + JSONArray list = jsonObject.getJSONArray("list"); + JSONObject listJSONObject = list.getJSONObject(0); + Long fs_id = listJSONObject.getLong("fs_id"); + String url = Constant.DOWN_LOUE_URL + "?method=filemetas&access_token=" + Constant.ATOKEN + "&fsids=[" + fs_id + "]&dlink=1"; + String s = HttpUtil.get(url); + JSONObject sJsonObject = new JSONObject(s); + JSONArray jsonArray = sJsonObject.getJSONArray("list"); + JSONObject jsonObjectClient = jsonArray.getJSONObject(0); + String dlink = jsonObjectClient.getStr("dlink"); + return dlink; + } + + /** + * @Description: TODO 创建文件 + * @param: fileName 文件名称 + * @param: size 文件大小 字节 + * @param: isDir 0文件 1目录(设置为目录是 size要设置为0) + * @param: blockList (文件的md5值) 可以把文件分为多个,然后分批上传 + * @return: java.lang.String + */ + private static String create(String fileName, Long size, Integer isDir, String blockList, String uploadid) { + String strURL = Constant.FILE_MANAGER_URL + "?method=create&access_token=" + Constant.ATOKEN; +// String params = "path=" + Constant.APP_PATH + fileName + "&size=" + size + "&autoinit=1&block_list=[\"" + blockList + "\"]&isdir=" + isDir +"&uploadid"+uploadid; +// return open(strURL, params, "POST"); +// +// //方式一 + HashMap<String, Object> paramMap = new HashMap<>(); + paramMap.put("path", Constant.APP_PATH + fileName); + paramMap.put("size", size); +// paramMap.put("autoinit", 1); +// paramMap.put("rtype", 1); + String str ="[\"" +blockList +"\"]"; + paramMap.put("block_list", str); + paramMap.put("isdir",isDir); + paramMap.put("uploadid",uploadid); +// paramMap.put("app_id",Constant.APP_ID); + String result= HttpUtil.post(strURL, paramMap); + System.out.println("block_list :" + paramMap.get("block_list")); + System.out.println("uploadid :" + paramMap.get("uploadid")); + System.out.println("path :" + paramMap.get("path")); +// + return result; + } + + /** + * @Description: TODO 分片上传 + * @param: path 上传到百度网盘的地址 + * @param: uploadid 上传的id + * @param: filePath 本地文件的地址 + * @return: java.lang.String + */ + private static String upload(String path, String uploadid, File[] files) { + try { + + for (int i = 0; i < files.length; i++) { + String url = Constant.SLICING_UPLOAD_FILE_URL + "?method=upload" + + "&access_token=" + Constant.ATOKEN + + "&type=tmpfile&partseq=" + i + + "&path=" + getURLEncoderString(path) + + "&uploadid=" + uploadid; + log.info("files : {} path {}",files[i], path); + //方式一 +// HashMap<String, Object> paramMap = new HashMap<>(); +// paramMap.put("file", FileUtil.file(files[i])); +// String result= HttpUtil.post(url, paramMap); + + //方式二 + String result = sendFile(url, files[i]); + log.info("正在上传分片文件{}{}", result, i); +// Thread.sleep(3000); + } + + return path; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + /** + * @Description: TODO 预上传 + * @param: cloudPath 云端路径 + * @param: size 文件大小 字节 + * @param: isDir 0文件 1目录(设置为目录是 size要设置为0) + * @param: blockList (文件的md5值) 可以把文件分为多个,然后分批上传 + * @return: java.lang.String + */ + private static String precreate(String cloudPath, Long size, Integer isDir, String blockList) { + String strURL = Constant.GET_READY_FILE_URL + "?method=precreate&access_token=" + Constant.ATOKEN; + String params = "path=" + getURLEncoderString(cloudPath) + "&size=" + size + "&autoinit=1&block_list=[\"" + blockList + "\"]&isdir=" + isDir; + return open(strURL, params, "POST"); + } + + + /** + * @Description: TODO 获取md5值 + * String path 文件地址 + */ + private final static String[] strHex = {"0", "1", "2", "3", "4", "5", + "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"}; + + private static String getMD5(File path) { + StringBuilder buffer = new StringBuilder(); + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + byte[] b = md.digest(org.apache.commons.io.FileUtils.readFileToByteArray(path)); + for (int value : b) { + int d = value; + if (d < 0) { + d += 256; + } + int d1 = d / 16; + int d2 = d % 16; + buffer.append(strHex[d1]).append(strHex[d2]); + } + return buffer.toString(); + } catch (Exception e) { + return null; + } + +// BigInteger bi = null; +// try { +// byte[] buffer = new byte[8192]; +// int len = 0; +// MessageDigest md = MessageDigest.getInstance("MD5"); +// +// FileInputStream fis = new FileInputStream(f); +// while ((len = fis.read(buffer)) != -1) { +// md.update(buffer, 0, len); +// } +// fis.close(); +// byte[] b = md.digest(); +// bi = new BigInteger(1, b); +// } catch (NoSuchAlgorithmException e) { +// e.printStackTrace(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// return bi.toString(16); + } + + + /** + * @Description: TODO + * @param: strURL 网址,可以是 http://aaa?bbb=1&ccc=2 拼接的 + * @param: params 拼接的body参数也就是form表单的参数 ddd=1&eee=2 + * @param: method 请求方式 get/post/put/delte等 + * @return: java.lang.String + */ + private static String open(String strURL, String params, String method) { + try { + URL url = new URL(strURL);// 创建连接 + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(true); + connection.setRequestMethod(method); + connection.setRequestProperty("Accept", "application/json");// 设置接收数据的格式 + connection.setRequestProperty("Content-Type", "application/json");// 设置发送数据的格式 + connection.connect(); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);// utf-8编码 + out.append(params); + out.flush(); + out.close(); // 读取响应 + int length = connection.getContentLength();// 获取长度 + InputStream is = connection.getInputStream(); + if (length != -1) { + byte[] data = new byte[length]; + byte[] temp = new byte[512]; + int readLen = 0; + int destPos = 0; + while ((readLen = is.read(temp)) > 0) { + System.arraycopy(temp, 0, data, destPos, readLen); + destPos += readLen; + } + return new String(data, StandardCharsets.UTF_8); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + /** + * 向指定 URL 发送POST方法的请求 + * + * @param url 发送请求的 URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return 所代表远程资源的响应结果 + */ + public static String sendFile(String url, String param, String file) { + if (url == null || param == null) { + return url; + } + + PrintWriter out = null; + BufferedReader in = null; + String result = ""; + try { + URL realUrl = new URL(url); + // 打开和URL之间的连接 + URLConnection conn = realUrl.openConnection(); + // 设置通用的请求属性 + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", + "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + // 发送POST请求必须设置如下两行 + conn.setDoOutput(true); + conn.setDoInput(true); + //设置链接超时时间为2秒 + conn.setConnectTimeout(1000); + //设置读取超时为2秒 + conn.setReadTimeout(1000); + // 获取URLConnection对象对应的输出流 + out = new PrintWriter(conn.getOutputStream()); + out.write(file); + // 发送请求参数 + out.print(param); + // flush输出流的缓冲 + out.flush(); + // 定义BufferedReader输入流来读取URL的响应 + in = new BufferedReader( + new InputStreamReader(conn.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println(e.getMessage() + "地址:" + url); + return null; + } + //使用finally块来关闭输出流、输入流 + finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + return null; + } + } + return result; + } + + + /** + * @param: filePath + * @param: unit 单个文件大小 + * @return: 返回文件的目录 + */ + private static File[] separate(Object obj, Integer unit) { + + try { + + InputStream bis = null;//输入流用于读取文件数据 + OutputStream bos = null;//输出流用于输出分片文件至磁盘 + File file = null; + if (obj instanceof String) { + file = new File((String) obj); + } + if (obj instanceof File) { + file = (File) obj; + } + + String filePath = file.getAbsolutePath(); + File newFile = new File(filePath.substring(0, filePath.lastIndexOf("\\") + 1)); + String directoryPath = newFile.getAbsolutePath(); + long splitSize = unit * 1024 * 1024;//单片文件大小,MB + if (file.length() < splitSize) { + log.info("文件小于单个分片大小,无需分片{}", file.length()); + return new File[]{file}; + } + + + //分片二 + RandomAccessFile in=null; + RandomAccessFile out =null; + long length=file.length();//文件大小 + long count=length%splitSize==0?(length/splitSize):(length/splitSize+1);//文件分片数 + byte[] bt=new byte[1024]; + in=new RandomAccessFile(file, "r"); + for (int i = 1; i <= count; i++) { + out = new RandomAccessFile(new File(filePath+"."+i), "rw");//定义一个可读可写且后缀名为.part的二进制分片文件 + long begin = (i-1)*splitSize; + long end = i* splitSize; + int len=0; + in.seek(begin); + while (in.getFilePointer()<end&&-1!=(len=in.read(bt))) { + out.write(bt, 0, len); + } + out.close(); + } + + + //分片一 +// bis = new BufferedInputStream(new FileInputStream(file)); +// long writeByte = 0;//已读取的字节数 +// int len = 0; +// byte[] bt = new byte[1024]; +// while (-1 != (len = bis.read(bt))) { +// if (writeByte % splitSize == 0) { +// if (bos != null) { +// bos.flush(); +// bos.close(); +// } +// bos = new BufferedOutputStream(new FileOutputStream(filePath + "." + (writeByte / splitSize + 1) + ".part")); +// } +// writeByte += len; +// bos.write(bt, 0, len); +// } + + + log.info("文件分片成功!"); + + //排除被分片的文件 + if (newFile.isDirectory()) { + File[] files = newFile.listFiles(); + File[] resultFiles = new File[files.length - 1]; + int j = 0; + for (int i = 0; i < files.length; i++) { + if (!files[i].equals(file)) { + resultFiles[j] = files[i]; + j++; + } + } + return resultFiles; + } + + bos.flush(); + bos.close(); + bis.close(); + return new File[0]; + } catch (Exception e) { + log.info("文件分片失败!"); + e.printStackTrace(); + } + return null; + } + + //splitNum:要分几片,currentDir:分片后存放的位置,subSize:按多大分片 + public static File[] nioSpilt(Object object, int splitNum, String currentDir, double subSize) { + try { + File file = null; + if (object instanceof String) { + file = new File((String) object); + } + if (object instanceof String) { + file = (File) object; + } + FileInputStream fis = new FileInputStream(file); + FileChannel inputChannel = fis.getChannel(); + FileOutputStream fos; + FileChannel outputChannel; + long splitSize = (long) subSize; + long startPoint = 0; + long endPoint = splitSize; + for (int i = 1; i <= splitNum; i++) { + fos = new FileOutputStream(currentDir + i); + outputChannel = fos.getChannel(); + inputChannel.transferTo(startPoint, splitSize, outputChannel); + startPoint += splitSize; + endPoint += splitSize; + outputChannel.close(); + fos.close(); + } + inputChannel.close(); + fis.close(); + File newFile = new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("\\") + 1)); + if (newFile.isDirectory()) { + return newFile.listFiles(); + } + } catch (Exception e) { + e.printStackTrace(); + } + return new File[0]; + } + + /** + * @Description: TODO 发送文件 + * @param: url 发送地址 + * @param: file 发送文件 + * @return: java.lang.String + */ + public static String sendFile(String url, File file) { + try { + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setContentType(ContentType.MULTIPART_FORM_DATA); + builder.addBinaryBody("file", file); + String body = ""; + //创建httpclient对象 + CloseableHttpClient client = HttpClients.createDefault(); + //创建post方式请求对象 + HttpPost httpPost = new HttpPost(url); + //设置请求参数 + HttpEntity httpEntity = builder.build(); + httpPost.setEntity(httpEntity); + //执行请求操作,并拿到结果(同步阻塞) + CloseableHttpResponse response = client.execute(httpPost); + //获取结果实体 + HttpEntity entity = response.getEntity(); + if (entity != null) { + //按指定编码转换结果实体为String类型 + body = EntityUtils.toString(entity, "utf-8"); + } + EntityUtils.consume(entity); + //释放链接 + response.close(); + return body; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + + public static String getURLEncoderString(String str) { + String result = ""; + if (null == str) { + return ""; + } + try { + result = java.net.URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return result; + } + + public static String URLDecoderString(String str) { + String result = ""; + if (null == str) { + return ""; + } + try { + result = java.net.URLDecoder.decode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return result; + } + + + + +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/UIDTest.java b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/UIDTest.java index 6b237be65..ae6e945a8 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/UIDTest.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/test/controller/UIDTest.java @@ -1,6 +1,7 @@ package com.ruoyi.web.test.controller; import cn.hutool.core.date.DateUtil; +import cn.hutool.http.HttpUtil; import com.github.wujun234.uid.UidGenerator; import com.ruoyi.bookmark.service.ISqMenuService; import com.ruoyi.common.core.redis.RedisUtil; @@ -80,4 +81,6 @@ public class UIDTest extends BaseSpringBootTest{ + + } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/BaiduUrl.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/BaiduUrl.java new file mode 100644 index 000000000..843e557c6 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/BaiduUrl.java @@ -0,0 +1,41 @@ +package com.ruoyi.common.constant; + +/** + * @Auther: Wang + * @Date: 2021/07/24 23:17 + * 功能描述: 百度网盘的 请求url + */ +public class BaiduUrl { + + /** + * 获取用户的身份信息 名称 + */ + public static final String USER = "https://pan.baidu.com/rest/2.0/xpan/nas"; + + /** + * 获取容量信息 + */ + public static final String CAPACITY = "https://pan.baidu.com/api/quota"; + + /** + * 获取文件列表 + */ + public static final String FILE_LIST = "https://pan.baidu.com/rest/2.0/xpan/file"; + + /** + * 获取递归文件列表 + */ + public static final String RECURSION = "https://pan.baidu.com/rest/2.0/xpan/multimedia"; + + /** + * 搜索文件 + */ + public static final String FILE_NAME = "https://pan.baidu.com/rest/2.0/xpan/file"; + + /** + * 通过ID查询文件的详细信息 + */ + public static final String FILEMETAS = "https://pan.baidu.com/rest/2.0/xpan/multimedia"; + + +} diff --git a/ruoyi-framework/pom.xml b/ruoyi-framework/pom.xml index 636c53928..bd8f227b0 100644 --- a/ruoyi-framework/pom.xml +++ b/ruoyi-framework/pom.xml @@ -79,6 +79,12 @@ <groupId>com.ruoyi</groupId> <artifactId>ruoyi-note</artifactId> </dependency> + <!-- 便签模块--> + <dependency> + <groupId>com.ruoyi</groupId> + <artifactId>yunpan-baidu</artifactId> + <version>3.0.0</version> + </dependency> </dependencies> diff --git a/ruoyi-ui/src/views/bookmark/bookmark/index.vue b/ruoyi-ui/src/views/bookmark/bookmark/index.vue index d56328706..5f16e59a5 100644 --- a/ruoyi-ui/src/views/bookmark/bookmark/index.vue +++ b/ruoyi-ui/src/views/bookmark/bookmark/index.vue @@ -10,7 +10,7 @@ src="https://favicon.lucq.fun/?url=https://www.baidu.com"/></div> </div> <div class="sousou-input" > - <el-input slot="reference" @keyup.enter.native="gosousuo" placeholder="请输入要查找的关键词" v-model="sousuo" + <el-input slot="reference" style="width: 300px;" @keyup.enter.native="gosousuo" placeholder="请输入要查找的关键词" v-model="sousuo" size="small" > <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input> @@ -1427,8 +1427,6 @@ .sousou-input { display: flex; - align-items: center; - justify-content: center; width: 100%; } diff --git a/yunpan-baidu/pom.xml b/yunpan-baidu/pom.xml new file mode 100644 index 000000000..3bbed169c --- /dev/null +++ b/yunpan-baidu/pom.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <artifactId>ruoyi</artifactId> + <groupId>com.ruoyi</groupId> + <version>3.0.0</version> + </parent> + <modelVersion>4.0.0</modelVersion> + + <artifactId>yunpan-baidu</artifactId> + + <description> + 云盘接口 + </description> + <dependencies> + + <!-- 通用工具--> + <dependency> + <groupId>com.ruoyi</groupId> + <artifactId>ruoyi-common</artifactId> + </dependency> + + </dependencies> +</project> diff --git a/yunpan-baidu/src/main/java/com/ruoyi/baidu/servise/BaiduWangPanServise.java b/yunpan-baidu/src/main/java/com/ruoyi/baidu/servise/BaiduWangPanServise.java new file mode 100644 index 000000000..094298883 --- /dev/null +++ b/yunpan-baidu/src/main/java/com/ruoyi/baidu/servise/BaiduWangPanServise.java @@ -0,0 +1,72 @@ +package com.ruoyi.baidu.servise; + + + +/** + * @Auther: Wang + * @Date: 2021/07/24 22:33 + * 功能描述: + */ + +public interface BaiduWangPanServise { + + + + /** + * @Description: 获取用户的身份信息 + * + * @param access_token token令牌 + * + */ + String getUserInfo(String access_token); + + /** + * @Description: 获取容量信息 + * + * @param access_token token令牌 + * + */ + String getCapacity(String access_token); + + /** + * @Description: 获取文件列表信息 + * + * @param access_token token令牌 + * + */ + String getFileList(String access_token); + + /** + * @Description: 获取文件列表信息 + * + * @param access_token token令牌 + * @param filePath 递归的文件夹路径 如: /myApp + * + */ + String getFileRecursionList(String access_token,String filePath); + + /** + * @Description: 搜索文件 + * + * @param access_token token令牌 + * @param fileName 文件名称 + * + */ + String getSouSuoFileList(String access_token,String fileName); + + /** + * @Description: 通过文件ID查询文件的信息 + * + * @param access_token token令牌 + * @param fileId 文件ID + * + */ + String getfilemetas(String access_token,String fileId); + + + + + + + +} diff --git a/yunpan-baidu/src/main/java/com/ruoyi/baidu/servise/impl/BaiduWangPanServiseImpl.java b/yunpan-baidu/src/main/java/com/ruoyi/baidu/servise/impl/BaiduWangPanServiseImpl.java new file mode 100644 index 000000000..5b66a2945 --- /dev/null +++ b/yunpan-baidu/src/main/java/com/ruoyi/baidu/servise/impl/BaiduWangPanServiseImpl.java @@ -0,0 +1,71 @@ +package com.ruoyi.baidu.servise.impl; + +import cn.hutool.http.HttpUtil; +import com.ruoyi.baidu.servise.BaiduWangPanServise; +import com.ruoyi.common.constant.BaiduUrl; +import org.springframework.stereotype.Service; + +import java.util.HashMap; + +/** + * @Auther: Wang + * @Date: 2021/07/24 22:34 + * 功能描述: 百度网盘操作 + */ +@Service +public class BaiduWangPanServiseImpl implements BaiduWangPanServise { + + + @Override + public String getUserInfo(String access_token) { + HashMap<String, Object> paramMap = new HashMap<>(); + paramMap.put("access_token", access_token); + paramMap.put("method", "uinfo"); + return HttpUtil.get(BaiduUrl.USER, paramMap); + } + + @Override + public String getCapacity(String access_token) { + HashMap<String, Object> paramMap = new HashMap<>(); + paramMap.put("access_token", access_token); + paramMap.put("checkfree", 1); + paramMap.put("checkexpire", 1); + return HttpUtil.get(BaiduUrl.CAPACITY, paramMap); + } + + @Override + public String getFileList(String access_token) { + HashMap<String, Object> paramMap = new HashMap<>(); + paramMap.put("access_token", access_token); + paramMap.put("method", "list"); + return HttpUtil.get(BaiduUrl.FILE_LIST, paramMap); + } + + @Override + public String getFileRecursionList(String access_token,String filePath) { + HashMap<String, Object> paramMap = new HashMap<>(); + paramMap.put("access_token", access_token); + paramMap.put("path", filePath); + return HttpUtil.get(BaiduUrl.RECURSION, paramMap); + } + + @Override + public String getSouSuoFileList(String access_token, String fileName) { + HashMap<String, Object> paramMap = new HashMap<>(); + paramMap.put("access_token", access_token); + paramMap.put("method", "search"); + paramMap.put("key", "imageAi"); + return HttpUtil.get(BaiduUrl.FILE_NAME, paramMap); + } + + @Override + public String getfilemetas(String access_token, String fileId) { + HashMap<String, Object> paramMap = new HashMap<>(); + paramMap.put("access_token", access_token); + paramMap.put("method", "filemetas"); + paramMap.put("fsids", fileId); + return HttpUtil.get(BaiduUrl.FILE_NAME, paramMap); + } + + +}