lyhzzz 3 gadi atpakaļ
vecāks
revīzija
ce6e21ab2b

+ 124 - 0
4dkankan-utils-file/pom.xml

@@ -0,0 +1,124 @@
+<?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>4dkankan-utils</artifactId>
+        <groupId>com.fdkankan</groupId>
+        <version>2.0.0</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>4dkankan-utils-file</artifactId>
+
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-context</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-beans</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+            <version>1.7.30</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-autoconfigure</artifactId>
+            <version>2.3.12.RELEASE</version>
+        </dependency>
+
+<!--        uploadToOssUtil-->
+        <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+            <version>2.8.3</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.amazonaws</groupId>
+            <artifactId>aws-java-sdk</artifactId>
+            <version>1.11.327</version>
+        </dependency>
+
+
+        <dependency>
+            <groupId>com.qiniu</groupId>
+            <artifactId>qiniu-java-sdk</artifactId>
+            <version>7.2.0</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.qiniu</groupId>
+            <artifactId>qiniu-java-sdk</artifactId>
+            <version>[7.2.0,7.2.99]</version>
+        </dependency>
+        <dependency>
+            <groupId>com.qiniu</groupId>
+            <artifactId>happy-dns-java</artifactId>
+            <version>0.1.4</version>
+            <scope>compile</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-pool2</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>commons-fileupload</groupId>
+            <artifactId>commons-fileupload</artifactId>
+            <version>1.4</version>
+            <scope>compile</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-webmvc</artifactId>
+            <version>5.3.13</version>
+        </dependency>
+        <dependency>
+            <groupId>com.google.code.gson</groupId>
+            <artifactId>gson</artifactId>
+            <version>2.8.5</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.bytedeco</groupId>
+            <artifactId>javacpp</artifactId>
+            <version>1.4.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.bytedeco</groupId>
+            <artifactId>javacv-platform</artifactId>
+            <version>1.4.3</version>
+        </dependency>
+        <dependency>
+            <groupId>joinery</groupId>
+            <artifactId>jave</artifactId>
+            <version>1.0.2.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.ant</groupId>
+            <artifactId>ant</artifactId>
+            <version>1.8.2</version>
+        </dependency>
+    </dependencies>
+
+
+
+</project>

+ 525 - 0
4dkankan-utils-file/src/main/java/com/fdkankan/file/oss/UploadToOssUtil.java

@@ -0,0 +1,525 @@
+package com.fdkankan.file.oss;
+
+import com.aliyun.oss.OSSClient;
+import com.aliyun.oss.model.OSSObjectSummary;
+import com.aliyun.oss.model.ObjectListing;
+import com.aliyun.oss.model.ObjectMetadata;
+import com.aliyun.oss.model.PutObjectResult;
+import com.amazonaws.HttpMethod;
+import com.amazonaws.auth.AWSStaticCredentialsProvider;
+import com.amazonaws.auth.BasicAWSCredentials;
+import com.amazonaws.regions.Regions;
+import com.amazonaws.services.s3.AmazonS3;
+import com.amazonaws.services.s3.AmazonS3ClientBuilder;
+import com.amazonaws.services.s3.model.CannedAccessControlList;
+import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
+import com.amazonaws.services.s3.model.GetObjectRequest;
+import com.amazonaws.services.s3.model.PutObjectRequest;
+import com.qiniu.common.Zone;
+import com.qiniu.storage.Configuration;
+import com.qiniu.storage.UploadManager;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileItemFactory;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.commons.CommonsMultipartFile;
+
+import java.io.*;
+import java.net.FileNameMap;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Slf4j
+@Component
+public class UploadToOssUtil {
+
+	Zone zone = Zone.autoZone();
+
+	Configuration config = new Configuration(zone);
+	UploadManager uploadManager = new UploadManager(config);
+
+	@Value("${oss.point:http://oss-cn-shenzhen-internal.aliyuncs.com}")
+	private String point;
+
+	@Value("${oss.key:LTAIUrvuHqj8pvry}")
+	private String key;
+
+	@Value("${oss.secrey:JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4}")
+	private String secrey;
+
+	@Value("${oss.bucket:4dkankan}")
+	private String bucket;
+
+	@Value("${oss.sdk:4dscene}")
+	private String bucketSdk;
+
+
+
+	@Value("${oss.type:oss}")
+	private String type;
+
+	@Value("${oss.s3key:AKIAWCV5QFZ3ZNELKYUY}")
+	private String s3key;
+
+	@Value("${oss.s3secrey:epS5ghyR4LJ7rxk/qJO9ZYh6m9Oz6g5haKDu4yws}")
+	private String s3secrey;
+
+	@Value("${oss.s3bucket:4dkankan}")
+	private String s3bucket;
+
+
+	public void delete(String key1) throws IOException{
+		OSSClient ossClient = new OSSClient(point, key, secrey);
+		try {
+			// bucketMgr.delete(bucketname, key);
+
+			// 2019-2-28 启动aliyun oss 空间
+			ossClient.deleteObject(bucket, key1);
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
+
+	//上传的数据是byte[],key是上传后的文件名
+	public void upload(byte[] data,String key1) throws IOException{
+		OSSClient ossClient = new OSSClient(point, key, secrey);
+		try
+		{
+
+			//bucketMgr.delete(bucketname, key);
+			//Response res = uploadManager.put(data, key, getUpToken(key));
+
+			// 2019-2-28 启动aliyun oss 空间
+			ossClient.putObject(bucket, key1, new ByteArrayInputStream(data));
+			//log.info(res.bodyString());
+		} catch (Exception e) {
+			log.error(e.toString()+key1);
+		}
+	}
+
+
+	public void upload(String filePath, String key1) {
+		log.info("开始上传文件 源路径:{},目标路径:{},point:{}" , filePath,key1,point);
+		if("oss".equals(type)){
+			OSSClient ossClient = new OSSClient(point, key, secrey);
+			try {
+				File file = new File(filePath);
+				if (!file.exists()) {
+					log.error("要上传的文件不存在:" + filePath);
+				}
+				ObjectMetadata metadata = new ObjectMetadata();
+				if(filePath.contains(".jpg")){
+					metadata.setContentType("image/jpeg");
+				}
+				ossClient.putObject(bucket, key1, new File(filePath), metadata);
+
+			} catch (Exception e) {
+				log.error(e.toString() + filePath);
+			}
+		}
+
+		if("s3".equals(type)){
+			try{
+				uploadS3File(filePath, key1);
+			}catch (Exception e){
+				e.printStackTrace();
+			}
+		}
+	}
+
+	public void uploadSdk(String filePath, String key1) {
+		if("oss".equals(type)){
+			OSSClient ossClient = new OSSClient(point, key, secrey);
+			try {
+				File file = new File(filePath);
+				if (!file.exists()) {
+					log.error("要上传的文件不存在:" + filePath);
+				}
+				// 调用put方法上传
+				// Response res = uploadManager.put(FilePath, key, getUpToken(key));
+				// 打印返回的信息
+				// log.info(res.bodyString());
+
+				// 2019-2-28 启动aliyun oss 空间
+//			ObjectMetadata meta = new ObjectMetadata();
+//			meta.setCacheControl("no-cache");
+//			ossClient.putObject(BUCKET_NAME, key, new File(filePath), meta);
+
+				ObjectMetadata metadata = new ObjectMetadata();
+				if(filePath.contains(".jpg")){
+					metadata.setContentType("image/jpeg");
+				}
+				ossClient.putObject(bucketSdk, key1, new File(filePath), metadata);
+
+			} catch (Exception e) {
+				log.error(e.toString() + filePath);
+			}
+		}
+
+		if("s3".equals(type)){
+			try{
+				uploadS3File(filePath, key1);
+			}catch (Exception e){
+				e.printStackTrace();
+			}
+		}
+	}
+
+	public void upload2(String filePath, String key1) {
+		log.info("开始上传文件 源路径:{},目标路径:{},point:{}" , filePath,key1,point);
+		if("oss".equals(type)){
+			OSSClient ossClient = new OSSClient(point, key, secrey);
+			try {
+				// 调用put方法上传
+				// Response res = uploadManager.put(FilePath, key, getUpToken(key));
+				// 打印返回的信息
+				// log.info(res.bodyString());
+
+				// 2019-2-28 启动aliyun oss 空间
+				ObjectMetadata metadata = new ObjectMetadata();
+				if(filePath.contains(".jpg")){
+					metadata.setContentType("image/jpeg");
+				}
+				if(filePath.contains(".mp4")){
+					metadata.setContentType("video/mp4");
+				}
+				if(filePath.contains(".mp3")){
+					metadata.setContentType("audio/mp3");
+				}
+				ossClient.putObject(bucket, key1, new File(filePath), metadata);
+			} catch (Exception e) {
+				log.error(e.toString() + filePath);
+			}
+		}
+
+		if("s3".equals(type)){
+			try{
+				uploadS3File(filePath, key1);
+			}catch (Exception e){
+				e.printStackTrace();
+			}
+		}
+	}
+
+	//上传的数据是文件夹,参数是文件夹路径,key是上传后的文件名
+	public void uploadMulFiles(Map<String, String> filepaths) {
+		if (filepaths == null) {
+			return;
+		}
+		Long start = System.currentTimeMillis();
+		log.info("开始批量上传文件:");
+		if (filepaths.size() > 50) {
+			filepaths.entrySet().parallelStream().forEach(entry->{
+				upload2(entry.getKey(), entry.getValue());
+			});
+		} else {
+			filepaths.entrySet().parallelStream().forEach(entry->{
+				upload(entry.getKey(), entry.getValue());
+			});
+		}
+		log.info("批量上传文件结束,用时:{}" ,(System.currentTimeMillis() - start));
+	}
+
+	public int deleteFile(String prefix){
+		if("oss".equals(type)){
+			OSSClient ossClient = new OSSClient(point, key, secrey);
+
+			ObjectListing objectListing = ossClient.listObjects(bucket, prefix);
+			List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
+			try {
+				for (OSSObjectSummary s : sums) {
+					delete(s.getKey());
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+
+		}
+
+		if("s3".equals(type)){
+			deleteS3Object(prefix);
+		}
+		return 1;
+	}
+
+
+	public Map<String, String> getUploadS3Url(List<String> urls){
+		if(urls == null || urls.size() <= 0){
+			return null;
+		}
+		BasicAWSCredentials awsCred = new BasicAWSCredentials(s3key, s3secrey);
+
+		AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
+				.withCredentials(new AWSStaticCredentialsProvider(awsCred))
+				.withRegion(Regions.EU_WEST_2)
+				.build();
+
+		// Set the pre-signed URL to expire after one hour.
+		java.util.Date expiration = new java.util.Date();
+		long expTimeMillis = expiration.getTime();
+		expTimeMillis += 1000 * 60 * 60 * 8;
+		expiration.setTime(expTimeMillis);
+
+		//生成预签名URL
+		log.info("生成预签名URL");
+		GeneratePresignedUrlRequest generatePresignedUrlRequest = null;
+		URL url = null;
+		Map<String, String> map = new HashMap();
+		for(String path : urls){
+//			if(path.contains(".jpg") || path.contains("png")){
+//				generatePresignedUrlRequest = new GeneratePresignedUrlRequest(s3bucket, path)
+//						.withMethod(HttpMethod.PUT)
+//						.withExpiration(expiration)
+//						.withContentType("image/jpeg");
+//			}else {
+				generatePresignedUrlRequest = new GeneratePresignedUrlRequest(s3bucket, path)
+						.withMethod(HttpMethod.PUT)
+						.withExpiration(expiration);
+//			}
+			url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
+			map.put(path, url.toString());
+		}
+		return map;
+	}
+
+
+	public String upload5(String filePath, String key1) {
+		OSSClient ossClient = new OSSClient(point, key, secrey);
+		PutObjectResult result = null;
+		try {
+			File file = new File(filePath);
+			if (!file.exists()) {
+				log.error("要上传的文件不存在:" + filePath);
+			}
+
+
+			result = ossClient.putObject(bucket, key1, new File(filePath));
+
+		} catch (Exception e) {
+			log.error(e.toString() + filePath);
+		}
+
+		log.info(" getETag : " + result.getETag());
+		log.info("1 : " + result.toString());
+		log.info("2 : " + result.getRequestId());
+		log.info("3 : " + result.getClientCRC());
+		log.info("4 : " + result.getResponse());
+		log.info("5 : " + result.getServerCRC());
+		return result.getETag();
+	}
+
+
+	//海外亚马逊s3
+
+
+	/**
+	 * s3上传文件流
+	 *
+	 * @param file       文件
+	 * @param updatePath 上传路径[ eg: xxx/xxx ]
+	 */
+	public String updateS3LoadFile(MultipartFile file, String updatePath) {
+
+		if (isEmpty(file)) {
+			return null;
+		}
+
+		/**
+		 * 创建s3对象
+		 */
+		BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
+		AmazonS3 s3 = AmazonS3ClientBuilder.standard()
+				.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
+				.withRegion(Regions.EU_WEST_2)
+				.build();
+
+		try {
+			// 创建临时文件,程序运行结束,会自动删除
+			File localFile = File.createTempFile("temp", null);
+			// 把文件写入内存中
+			file.transferTo(localFile);
+
+			// 指定要上传到服务器上的路径
+			String key = updatePath;
+
+			// 设置文件并设置公读
+			PutObjectRequest request = new PutObjectRequest(s3bucket, key, localFile);
+			request.withCannedAcl(CannedAccessControlList.PublicRead);
+
+			// 上传文件
+			com.amazonaws.services.s3.model.PutObjectResult putObjectResult = s3.putObject(request);
+			if (StringUtils.isNotEmpty(putObjectResult.getETag())) {
+				System.out.println("success");
+				return key;
+			}
+			return null;
+
+		} catch (IOException e) {
+		}
+		return null;
+	}
+
+	/**
+	 * s3上传文件
+	 * @param filePath
+	 * @param key1
+	 * @throws IOException
+     */
+	private void uploadS3File(String filePath, String key1) throws IOException {
+		File file = new File(filePath);
+		if(!file.exists()){
+			log.info("要上传s3的文件不存在");
+			return;
+		}
+
+		/**
+		 * 创建s3对象
+		 */
+		BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
+		AmazonS3 s3 = AmazonS3ClientBuilder.standard()
+				.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
+				.withRegion(Regions.EU_WEST_2)
+				.build();
+
+		// 设置文件并设置公读
+		com.amazonaws.services.s3.model.ObjectMetadata metadata = new com.amazonaws.services.s3.model.ObjectMetadata();
+		if(filePath.contains(".jpg")){
+			metadata.setContentType("image/jpeg");
+		}
+		if(filePath.contains(".png")){
+			metadata.setContentType("image/png");
+		}
+		PutObjectRequest request = new PutObjectRequest(s3bucket, key1, file);
+		request.withCannedAcl(CannedAccessControlList.PublicRead);
+		request.withMetadata(metadata);
+
+		// 上传文件
+		com.amazonaws.services.s3.model.PutObjectResult putObjectResult = s3.putObject(request);
+		if (StringUtils.isNotEmpty(putObjectResult.getETag())) {
+			log.info("s3上传文件成功:" + key1);
+		}
+	}
+
+	/**
+	 * 删除单个文件
+	 *
+	 * @param filePath 文件路径[ eg: /head/xxxx.jpg ]
+	 * @return
+	 */
+	public void deleteS3Object(String filePath) {
+
+		/**
+		 * 创建s3对象
+		 */
+		BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
+		AmazonS3 s3 = AmazonS3ClientBuilder.standard()
+				.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
+				.withRegion(Regions.EU_WEST_2)
+				.build();
+
+		if (filePath.startsWith("/")) {
+			filePath = filePath.substring(1);
+		}
+
+		try {
+			s3.deleteObject(s3bucket, filePath);
+		} catch (Exception e) {
+		}
+	}
+
+
+
+	/**
+	 * 获取文件类型
+	 */
+	public static String getContentType(String filePath){
+		FileNameMap fileNameMap = URLConnection.getFileNameMap();
+		String contentType = fileNameMap.getContentTypeFor(filePath);
+		System.out.println(contentType);
+		return contentType;
+
+	}
+
+	/**
+	 * 检查文件是否为空
+	 *
+	 * @param imageFile
+	 * @return
+	 */
+	private static boolean isEmpty(MultipartFile imageFile) {
+		if (imageFile == null || imageFile.getSize() <= 0) {
+			return true;
+		}
+		return false;
+	}
+
+	private static MultipartFile getMulFileByPath(String picPath) {
+		FileItem fileItem = createFileItem(picPath);
+		MultipartFile mfile = new CommonsMultipartFile(fileItem);
+		return mfile;
+	}
+
+	private static FileItem createFileItem(String filePath)
+	{
+		FileItemFactory factory = new DiskFileItemFactory(16, null);
+		String textFieldName = "textField";
+		int num = filePath.lastIndexOf(".");
+		String extFile = filePath.substring(num);
+		FileItem item = factory.createItem(textFieldName, "text/plain", true,
+				"MyFileName" + extFile);
+		File newfile = new File(filePath);
+		int bytesRead = 0;
+		byte[] buffer = new byte[8192];
+		try
+		{
+			FileInputStream fis = new FileInputStream(newfile);
+			OutputStream os = item.getOutputStream();
+			while ((bytesRead = fis.read(buffer, 0, 8192))
+					!= -1)
+			{
+				os.write(buffer, 0, bytesRead);
+			}
+			os.close();
+			fis.close();
+		}
+		catch (IOException e)
+		{
+			e.printStackTrace();
+		}
+		return item;
+	}
+
+	/**
+	 * 下载文件
+	 * @param bucketName	桶名
+	 * @param remoteFileName	文件名
+	 * @param path	下载路径
+	 */
+	public boolean downFromS3(String bucketName, String remoteFileName, String path) {
+		try {
+			/**
+			 * 创建s3对象
+			 */
+			BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
+			AmazonS3 s3 = AmazonS3ClientBuilder.standard()
+					.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
+					.withRegion(Regions.EU_WEST_2)
+					.build();
+
+			GetObjectRequest request  = new GetObjectRequest(bucketName,remoteFileName);
+			s3.getObject(request,new File(path));
+			return true;
+		} catch (Exception ase) {
+			log.error("amazonS3下载文件异常 " + ase.getMessage(), ase);
+		}
+		return false;
+	}
+
+}

+ 169 - 0
4dkankan-utils-file/src/main/java/com/fdkankan/file/qiniu/QiniuUpload.java

@@ -0,0 +1,169 @@
+package com.fdkankan.file.qiniu;
+
+import com.google.gson.Gson;
+import com.qiniu.cdn.CdnManager;
+import com.qiniu.cdn.CdnResult;
+import com.qiniu.common.QiniuException;
+import com.qiniu.http.Response;
+import com.qiniu.storage.BucketManager;
+import com.qiniu.storage.Configuration;
+import com.qiniu.storage.UploadManager;
+import com.qiniu.storage.model.DefaultPutRet;
+import com.qiniu.util.Auth;
+import com.qiniu.util.StringMap;
+import com.qiniu.util.UrlSafeBase64;
+
+import java.io.File;
+
+public class QiniuUpload {
+
+	//删除文件
+	public static void delete(String key) throws QiniuException{
+		Configuration cfg = new Configuration(QiniuUtil.zone);
+		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
+		BucketManager bucketManager = new BucketManager(auth, cfg);
+        bucketManager.delete(QiniuUtil.bucket, key);
+	}
+
+	//刷新文件
+	public static void refresh(String url) throws QiniuException{
+		String [] urls = {url};
+		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
+		CdnManager c = new CdnManager(auth);
+		CdnResult.RefreshResult response = c.refreshUrls(urls);
+	}
+
+
+	/**
+	 * 上传单个文件到七牛云
+	 * @param key
+	 * @param localFilePath
+	 */
+	public static boolean setFileToBucket(String key, String localFilePath){
+		Configuration cfg = new Configuration(QiniuUtil.zone);
+		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
+		UploadManager uploadManager = new UploadManager(cfg);
+		
+		String upToken = auth.uploadToken(QiniuUtil.bucket);
+		
+		try {
+		    Response response = uploadManager.put(localFilePath, key, upToken);
+		    //解析上传成功的结果
+		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
+		    System.out.println(putRet.key);
+		    System.out.println(putRet.hash);
+		    return true;
+		} catch (QiniuException ex) {
+		    Response r = ex.response;
+		    System.err.println(r.toString());
+		    try {
+		        System.err.println(r.bodyString());
+		    } catch (QiniuException ex2) {
+		    }
+		    return false;
+		}
+	}
+	
+	/**
+	 * 上传本地目录下所有文件到七牛云上
+	 * @param remoteFolder
+	 * @param localFolderPath
+	 */
+	public static void setFilesToBucket(String remoteFolder, String localFolderPath) {
+		Configuration cfg = new Configuration(QiniuUtil.zone);
+		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
+		UploadManager uploadManager = new UploadManager(cfg);
+		
+		File file = new File(localFolderPath);
+		File[] files = file.listFiles();// 获取目录下的所有文件或文件夹
+		if (files == null) {// 如果目录为空,直接退出
+			return;
+		}
+
+		// 遍历,目录下的所有文件
+		for (File f : files) {
+			if (f.isFile()) {
+				String key = f.getName();
+				if (remoteFolder != null) {
+					key = remoteFolder + key;
+				} 
+				// 再上传文件
+				String upToken = auth.uploadToken(QiniuUtil.bucket);
+				try {
+					Response res = uploadManager.put(f, key, upToken);
+					System.out.println(res.bodyString());
+				} catch (QiniuException e) {
+					Response r = e.response;
+					System.err.println(r.toString());
+					try {
+						System.err.println(r.bodyString());
+					} catch (QiniuException ex2) {
+					}
+				}
+			} else if (f.isDirectory()) {
+				String key = f.getName() + "/";
+				if (remoteFolder != null) {
+					key = remoteFolder + key;
+				}
+				setFilesToBucket(key, f.getAbsolutePath());
+			}
+		}
+	}
+
+	/**
+	 * 测试七牛上传后,自动进行数据处理操作,并另存处理后的文件
+	 * @param domain 存储空间所对应的域名
+	 * @param file 上传文件
+	 */
+	public static void testFops(String domain, File file) {
+		//通过AK,SK创建Auth 对象
+		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
+		Configuration cfg = new Configuration(QiniuUtil.zone);
+		//上传对象
+		UploadManager uploadMgr = new UploadManager(cfg);
+		//私有队列
+		String pipeline = "av-pipeline";
+		//水印文字
+		String wmText = UrlSafeBase64.encodeToString("Word For Test");
+		//水印文字的颜色
+		String wmFontColor = UrlSafeBase64.encodeToString("#FFFF00");
+		//设置avthumb 接口
+		StringBuffer ops = new StringBuffer("");
+		ops.append("avthumb/mp4/wmText/" + wmText +"/wmGravityText/NorthEast/wmFontColor/" + wmFontColor);
+		String saveAs = UrlSafeBase64.encodeToString(QiniuUtil.bucket + ":" + "new_" + file.getName());
+		//通过管道符 "|" 拼接 saveas 接口, 保存 数据处理后的视频
+		ops.append("|saveas/" + saveAs);
+		//saveas 接口 需要签名 sign
+		String sign = domain + "/" + file.getName() + "?" + ops.toString();
+		String encodeSign = UrlSafeBase64.encodeToString(sign);
+		ops.append("/sign/" + encodeSign);
+		//指定 数据处理 的 上传策略, 当文件上传成功后,自定执行数据处理操作,即:ops 的接口,图片加水印,另存为 new_file.getName();
+		StringMap putPolicy = new StringMap();
+		putPolicy.put("persistentOps", ops.toString())      //数据处理接口及参数
+				.put("persistentPipeline", pipeline);      //私有数据处理队列
+
+		//获取上传凭证, 包含上传策略
+		String uploadToken = auth.uploadToken(QiniuUtil.bucket, file.getName(), 3600, putPolicy);
+
+		try {
+			//上传
+			Response resp = uploadMgr.put(file, file.getName(), uploadToken);
+			//查看结果
+			System.out.println(resp.statusCode + ":" + resp.bodyString());
+		} catch (QiniuException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+
+	}
+
+    public static void main(String[] args) {
+        QiniuUpload upload = new QiniuUpload();
+        try {
+            QiniuUpload.delete("head/13211064273/head.png");
+//            QiniuUpload.refresh("http://scene3d.4dage.com/head/13211064273/head.png");
+        } catch (QiniuException e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 262 - 0
4dkankan-utils-file/src/main/java/com/fdkankan/file/qiniu/QiniuUtil.java

@@ -0,0 +1,262 @@
+package com.fdkankan.file.qiniu;
+
+import com.qiniu.common.Zone;
+import com.qiniu.util.Auth;
+import com.qiniu.util.UrlSafeBase64;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.protocol.HTTP;
+import org.apache.http.util.EntityUtils;
+
+import java.io.IOException;
+import java.net.URLEncoder;
+
+public class QiniuUtil {
+
+    public static String accessKey = "dlPPwgZky_F-iP8CbSbJpiAtAcqw3BYwb9rdHMrS";
+    public static String secretKey = "YEtkLKDsImXB-8m1CT1zV_YwCwwGvrUvo2ktj9KZ";
+    public static Zone zone = Zone.zone1();
+    public static String bucket = "scene3d";
+    public static String remoteUrl = "https://4dkanzhan.4dkankan.com/";
+
+    public static void main(String[] args) throws IOException {
+//        crop4K("4k.jpg", "http://www.baidu.com");
+//        thumb("test111.jpg", "128", "128", "http://www.baidu.com");
+
+        /*try{
+            File f = new File("D:/usr/local/szggkfzlg/upload/20190125181036.png");
+            FileInputStream fi = new FileInputStream(f);
+            try{
+                BufferedImage sourceImg =ImageIO.read(fi);//判断图片是否损坏
+                int picWidth= sourceImg.getWidth(); //确保图片是正确的(正确的图片可以取得宽度)
+            }catch (Exception e) {
+                // TODO: handle exception
+                fi.close();//关闭IO流才能操作图片
+            }finally{
+                fi.close();//最后一定要关闭IO流
+            }
+        }catch (Exception e  ) {
+            // TODO: handle exception
+            System.out.println(e.toString());
+        }*/
+
+        getVideoFrame("a.mp4", "png", "6.010", null, null, null, "a_framw.png", "http://www.baidu.com");
+    }
+
+    /**
+     * 视频帧缩略图接口(vframe)用于从视频流中截取指定时刻的单帧画面并按指定大小缩放成图片
+     * @param key 文件名  a.mp4
+     * @param suffixName 输出的目标截图格式,支持jpg、png等。
+     * @param second 指定截取视频的时刻,单位:秒,精确到毫秒。
+     * @param width 缩略图宽度,单位:像素(px),取值范围为1-3840, 可不传。
+     * @param height 缩略图高度,单位:像素(px),取值范围为1-2160, 可不传。
+     * @param rotate 指定顺时针旋转的度数,可取值为90、180、270、auto,默认为不旋转,可不传。
+     * @param newKey 新文件名称
+     * @param notifyURL 回调地址
+     * @throws IOException
+     */
+    public static void getVideoFrame(String key, String suffixName, String second, Integer width, Integer height, Integer rotate, String newKey, String notifyURL) throws IOException {
+        StringBuffer sb = new StringBuffer("vframe/").append(suffixName).append("/offset/").append(second);
+        if (width != null){
+            sb.append("/w/").append(width);
+        }
+        if (height != null){
+            sb.append("/h/").append(height);
+        }
+        if (rotate != null){
+            sb.append("/rotate/").append(rotate);
+        }
+
+        String fop = URLEncoder.encode(sb.toString(), "utf-8");
+        StringBuffer ops = new StringBuffer("bucket=").append(bucket).append("&key=").append(key).append("&fops=").append(fop);
+        String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + newKey);
+        ops.append("|saveas/").append(saveAs);
+
+        ops.append("&notifyURL=").append(notifyURL);
+
+        HttpPost post = new HttpPost("http://api.qiniu.com/pfop/");
+        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
+        StringEntity entity = new StringEntity(ops.toString(), "utf-8");
+        entity.setContentType("application/x-www-form-urlencoded");
+        post.setEntity(entity);
+
+        Auth auth = Auth.create(accessKey, secretKey);
+        String si = auth.signRequest("http://api.qiniu.com/pfop/", ops.toString().getBytes(), "application/x-www-form-urlencoded");
+        post.setHeader("Authorization", "QBox " + si);
+        HttpClient client = new DefaultHttpClient();
+        HttpResponse res = client.execute(post);
+        String ret = EntityUtils.toString(res.getEntity(), "UTF-8");
+        System.out.println(ret);
+
+    }
+
+    /**
+     * 给视频添加水印
+     * @param key a.mp4
+     * @param text  4dage
+     * @param fontColor #FFFF00
+     * @param newKey new_a.mp4
+     * @param notifyURL 回调地址
+     * @throws IOException
+     */
+    public static void waterMark(String key, String text, String fontColor, String newKey, String notifyURL) throws IOException {
+        String fop = "avthumb/mp4/";
+        fop = URLEncoder.encode(fop, "utf-8");
+        //水印文字
+        String wmText = UrlSafeBase64.encodeToString(text);
+        //水印文字的颜色
+        String wmFontColor = UrlSafeBase64.encodeToString(fontColor);
+        //设置avthumb 接口
+        StringBuffer ops = new StringBuffer("bucket=").append(bucket).append("&key=").append(key).append("&fops=").append(fop);
+        ops.append("avthumb/mp4/wmText/").append(wmText).append("/wmGravityText/NorthEast/wmFontColor/").append(wmFontColor);
+        String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + newKey);
+        ops.append("|saveas/").append(saveAs);
+        ops.append("&notifyURL=").append(notifyURL);
+
+        HttpPost post = new HttpPost("http://api.qiniu.com/pfop/");
+        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
+        StringEntity entity = new StringEntity(ops.toString(), "utf-8");
+        entity.setContentType("application/x-www-form-urlencoded");
+        post.setEntity(entity);
+
+        Auth auth = Auth.create(accessKey, secretKey);
+        String si = auth.signRequest("http://api.qiniu.com/pfop/", ops.toString().getBytes(), "application/x-www-form-urlencoded");
+        post.setHeader("Authorization", "QBox " + si);
+        HttpClient client = new DefaultHttpClient();
+        HttpResponse res = client.execute(post);
+        String ret = EntityUtils.toString(res.getEntity(), "UTF-8");
+        System.out.println(ret);
+    }
+
+    /**
+     * 将4K图片裁剪成64张512*512
+     * @param key
+     * @param notifyURL  回调地址 "http://wwww.cn/qn/notify&force=1"
+     * @throws IOException
+     */
+    public static void crop4K(String key, String notifyURL) throws IOException {
+        String fop = "imageMogr2/auto-orient/";
+        fop = URLEncoder.encode(fop, "utf-8");
+
+        String fileName = key.substring(0, key.lastIndexOf("."));
+        String suffixName = key.substring(key.lastIndexOf("."));
+
+        Auth auth = Auth.create(accessKey, secretKey);
+
+        for (int i = 0; i < 8; i++) {
+            for (int j = 0; j < 8; j++) {
+                String ret = crop(key, notifyURL, fop, fileName, suffixName, auth, i, j);
+                System.out.println(ret);
+            }
+        }
+    }
+
+    /**
+     * 将2K图片裁剪成16张512*512
+     * @param key
+     * @param notifyURL 回调地址 "http://wwww.cn/qn/notify&force=1"
+     * @throws IOException
+     */
+    public static void crop2k(String key, String notifyURL) throws IOException {
+        String fop = "imageMogr2/auto-orient/";
+        fop = URLEncoder.encode(fop, "utf-8");
+
+        String fileName = key.substring(0, key.lastIndexOf("."));
+        String suffixName = key.substring(key.lastIndexOf("."));
+
+        Auth auth = Auth.create(accessKey, secretKey);
+
+        for (int i = 0; i < 4; i++) {
+            for (int j = 0; j < 4; j++) {
+                String ret = crop(key, notifyURL, fop, fileName, suffixName, auth, i, j);
+                System.out.println(ret);
+            }
+        }
+    }
+
+    /**
+     * 将1K图片裁剪成4张512*512
+     * @param key
+     * @param notifyURL 回调地址 "http://wwww.cn/qn/notify&force=1"
+     * @throws IOException
+     */
+    public static void crop1k(String key, String notifyURL) throws IOException {
+        String fop = "imageMogr2/auto-orient/";
+        fop = URLEncoder.encode(fop, "utf-8");
+
+        String fileName = key.substring(0, key.lastIndexOf("."));
+        String suffixName = key.substring(key.lastIndexOf("."));
+
+        Auth auth = Auth.create(accessKey, secretKey);
+
+        for (int i = 0; i < 2; i++) {
+            for (int j = 0; j < 2; j++) {
+                String ret = crop(key, notifyURL, fop, fileName, suffixName, auth, i, j);
+                System.out.println(ret);
+            }
+        }
+    }
+
+    private static String crop(String key, String notifyURL, String fop, String fileName, String suffixName, Auth auth, int i, int j) throws IOException {
+        StringBuffer ops = new StringBuffer("bucket=").append(bucket).append("&key=").append(key).append("&fops=").append(fop);
+        ops.append("crop/!512x512a" + j * 512 + "a" + i * 512);
+
+        String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + fileName + "_" + j + "_" + i + suffixName);
+        ops.append("|saveas/").append(saveAs);
+        ops.append("&notifyURL=").append(notifyURL);
+        HttpPost post = new HttpPost("http://api.qiniu.com/pfop/");
+        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
+        StringEntity entity = new StringEntity(ops.toString(), "utf-8");
+        entity.setContentType("application/x-www-form-urlencoded");
+        post.setEntity(entity);
+
+        String si = auth.signRequest("http://api.qiniu.com/pfop/", ops.toString().getBytes(), "application/x-www-form-urlencoded");
+        post.setHeader("Authorization", "QBox " + si);
+        HttpClient client = new DefaultHttpClient();
+        HttpResponse res = client.execute(post);
+        return EntityUtils.toString(res.getEntity(), "UTF-8");
+    }
+
+    /**
+     * 将七牛云上的图片缩放成指定大小的图片
+     * @param key
+     * @param width
+     * @param height
+     * @param notifyURL
+     * @throws IOException
+     */
+    public static void thumb(String key, String width, String height, String notifyURL, String newKey) throws IOException {
+        String fop = "imageMogr2/auto-orient/";
+        fop = URLEncoder.encode(fop, "utf-8");
+
+        String fileName = key.substring(0, key.lastIndexOf("."));
+        String suffixName = key.substring(key.lastIndexOf("."));
+
+        Auth auth = Auth.create(accessKey, secretKey);
+
+        StringBuffer ops = new StringBuffer("bucket=").append(bucket).append("&key=").append(key).append("&fops=").append(fop);
+        ops.append("thumbnail/"+width+"x"+height+"!");
+
+        //saveAs新生成文件的名称
+        newKey = StringUtils.isNotEmpty(newKey) ? newKey : (fileName + "_thumb" + suffixName);
+        String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + newKey);
+        ops.append("|saveas/").append(saveAs);
+        ops.append("&notifyURL=").append(notifyURL);
+        HttpPost post = new HttpPost("http://api.qiniu.com/pfop/");
+        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
+        StringEntity entity = new StringEntity(ops.toString(), "utf-8");
+        entity.setContentType("application/x-www-form-urlencoded");
+        post.setEntity(entity);
+
+        String si = auth.signRequest("http://api.qiniu.com/pfop/", ops.toString().getBytes(), "application/x-www-form-urlencoded");
+        post.setHeader("Authorization", "QBox " + si);
+        HttpClient client = new DefaultHttpClient();
+        HttpResponse res = client.execute(post);
+        System.out.println(EntityUtils.toString(res.getEntity(), "UTF-8"));
+    }
+
+}

+ 133 - 0
4dkankan-utils-file/src/main/java/com/fdkankan/file/utils/FileMd5Util.java

@@ -0,0 +1,133 @@
+package com.fdkankan.file.utils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.security.MessageDigest;
+
+public class FileMd5Util {
+
+    public static final String KEY_MD5 = "MD5";
+    public static final String CHARSET_ISO88591 = "ISO-8859-1";
+
+    /**
+     * Get MD5 of one file:hex string,test OK!
+     *
+     * @param file
+     * @return
+     */
+    public static String getFileMD5(File file) {
+        if (!file.exists() || !file.isFile()) {
+            return null;
+        }
+        MessageDigest digest = null;
+        FileInputStream in = null;
+        byte buffer[] = new byte[1024];
+        int len;
+        try {
+            digest = MessageDigest.getInstance("MD5");
+            in = new FileInputStream(file);
+            while ((len = in.read(buffer, 0, 1024)) != -1) {
+                digest.update(buffer, 0, len);
+            }
+            in.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+        byte by[] = digest.digest();
+        int i;
+        StringBuffer sbf = new StringBuffer();
+        for (int j = 0; j < by.length; j++) {
+            i = by[j];
+            if (i < 0) {
+                i += 256;
+            } else if (i < 16) {
+                sbf.append("0");    //因为大于16的有两位,因此小于16需要补位,
+            }
+            sbf.append(Integer.toHexString(i));
+
+        }
+
+        return sbf.toString();
+//        BigInteger bigInt = new BigInteger(1, digest.digest());
+//        return bigInt.toString(16);
+    }
+
+    /***
+     * Get MD5 of one file!test ok!
+     *
+     * @param filepath
+     * @return
+     */
+    public static String getFileMD5(String filepath) {
+        File file = new File(filepath);
+        return getFileMD5(file);
+    }
+
+    /**
+     * MD5 encrypt,test ok
+     *
+     * @param data
+     * @return byte[]
+     * @throws Exception
+     */
+    public static byte[] encryptMD5(byte[] data) throws Exception {
+
+        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
+        md5.update(data);
+        return md5.digest();
+    }
+
+    public static byte[] encryptMD5(String data) throws Exception {
+        return encryptMD5(data.getBytes(CHARSET_ISO88591));
+    }
+
+    /***
+     * compare two file by Md5
+     *
+     * @param file1
+     * @param file2
+     * @return
+     */
+    public static boolean isSameMd5(File file1, File file2) {
+        String md5_1 = FileMd5Util.getFileMD5(file1);
+        String md5_2 = FileMd5Util.getFileMD5(file2);
+        return md5_1.equals(md5_2);
+    }
+
+    /***
+     * compare two file by Md5
+     *
+     * @param filepath1
+     * @param filepath2
+     * @return
+     */
+    public static boolean isSameMd5(String filepath1, String filepath2) {
+        File file1 = new File(filepath1);
+        File file2 = new File(filepath2);
+        return isSameMd5(file1, file2);
+    }
+
+    public static void main(String[] args){
+//        String path = "F:\\桌面\\";
+//
+//        StringBuffer sb = new StringBuffer(path + "20190925151119.h264");
+//        File dbFile = new File(sb.toString());
+//
+//        String fileMD5 = FileMd5Util.getFileMD5(dbFile);
+//        System.out.println(fileMD5);
+
+//        String path1 = "F:\\文档\\WeChat Files\\Iove-bing\\FileStorage\\File\\2020-05\\1.3.4-update.zip";
+//        File dbFile1 = new File(path1);
+//
+//        String fileMD51 = FileMd5Util.getFileMD5(dbFile1);
+//        System.out.println(fileMD51);
+
+//        BigInteger usedSpace = new BigInteger("0");
+//        BigInteger space = new BigInteger("560800515");
+//        usedSpace.add(space);
+//        System.out.println(usedSpace.intValue());
+        System.out.println("obj1: " + getFileMD5(new File("F:\\桌面\\c11m-T11-EA\\log\\i6VhiQ2Q-copy.obj")));
+        System.out.println("obj: " + getFileMD5(new File("F:\\桌面\\c11m-T11-EA\\log\\i6VhiQ2Q.obj")));
+    }
+}

+ 141 - 0
4dkankan-utils-file/src/main/java/com/fdkankan/file/utils/FileSizeUtil.java

@@ -0,0 +1,141 @@
+package com.fdkankan.file.utils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.text.DecimalFormat;
+
+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 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();
+        }
+        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();
+        }
+        return formatFileSize(blockSize);
+    }
+
+    /**
+     * 获取指定文件大小
+     */
+    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();
+        }
+        return size;
+    }
+
+    /**
+     * 获取指定文件夹
+     */
+    private static long getFileSizes(File f) throws Exception {
+        long size = 0;
+        File flist[] = f.listFiles();
+        assert flist != null;
+        for (File file : flist) {
+            if (file.isDirectory()) {
+                size = size + getFileSizes(file);
+            } else {
+                size = size + getFileSize(file);
+            }
+        }
+        return size;
+    }
+
+    /**
+     * 转换文件大小
+     */
+    public static String formatFileSize(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 if (fileS < 1099511627776L){
+            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
+        } else if (fileS < 1125899906842624L){
+            fileSizeString = df.format((double) fileS / 1099511627776L) + "TB";
+        } else {
+            fileSizeString = df.format((double) fileS / 1125899906842624L) + "PB";
+        }
+        return fileSizeString;
+    }
+
+    /**
+     * 转换文件大小,指定转换的类型
+     */
+    public 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;
+    }
+}

+ 134 - 0
4dkankan-utils-file/src/main/java/com/fdkankan/file/utils/FileUpload.java

@@ -0,0 +1,134 @@
+package com.fdkankan.file.utils;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.*;
+
+/**
+ * @author MeepoGuan
+ *
+ * <p>Description: 上传问题件</p>
+ *
+ * 2017年4月30日
+ *
+ */
+@Slf4j
+public class FileUpload {
+
+	/**
+	 * @param file 			//文件对象
+	 * @param filePath		//上传路径
+	 * @param fileName		//文件名
+	 * @return  文件名
+	 */
+	public static String fileUp(MultipartFile file, String filePath, String fileName) throws IOException {
+		String extName = ""; // 扩展名格式:
+
+		if (file.getOriginalFilename().lastIndexOf(".") >= 0){
+			extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
+		}
+		copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
+
+		return fileName+extName;
+	}
+	
+	/**
+	 * 写文件到当前目录的upload目录中
+	 * 
+	 * @param in
+	 * @param dir
+	 * @param realName
+	 * @throws IOException
+	 */
+	private static String copyFile(InputStream in, String dir, String realName)
+			throws IOException {
+		File file = new File(dir, realName);
+		if (!file.exists()) {
+			if (!file.getParentFile().exists()) {
+				file.getParentFile().mkdirs();
+			}
+			file.createNewFile();
+		}
+        org.apache.commons.io.FileUtils.copyInputStreamToFile(in, file);
+		return realName;
+	}
+
+	/**
+	 * 断点续传
+	 * @param
+     */
+	public static String fileUpAgain(InputStream in, String filePath, String fileName, String realSavePath) throws IOException {
+		try{
+			File realFile = new File(realSavePath +  fileName);
+			File tempFile = new File(filePath + fileName);
+			if(!realFile.getParentFile().exists()){
+				realFile.getParentFile().mkdirs();
+			}
+			if(!tempFile.getParentFile().exists()){
+				tempFile.getParentFile().mkdirs();
+			}
+
+//			InputStream in = file.getInputStream();
+			long needSkipBytes = 0;
+			if (tempFile.exists()) {//续传
+				needSkipBytes = tempFile.length();
+			} else {//第一次传
+				tempFile.createNewFile();
+			}
+			log.info("跳过的字节数为:" + needSkipBytes);
+			in.skip(needSkipBytes);
+			RandomAccessFile tempRandAccessFile = new RandomAccessFile(tempFile, "rw");
+			tempRandAccessFile.seek(needSkipBytes);
+			byte[] buffer = new byte[1024];
+			int len = 0;
+			int count = 0;
+			while ((len = in.read(buffer)) > 0) {
+				tempRandAccessFile.write(buffer);
+				count++;
+			}
+			in.close();
+			tempRandAccessFile.close();
+			realFile.createNewFile();
+			if (fileCopy(tempFile, realFile)) {
+				tempFile.delete();
+			}
+		}catch (Exception e){
+			e.printStackTrace();
+		}
+		return realSavePath + fileName;
+	}
+
+	private static boolean fileCopy(File sourceFile, File targetFile) {
+		boolean success = true;
+		try {
+			FileInputStream in = new FileInputStream(sourceFile);
+			FileOutputStream out = new FileOutputStream(targetFile);
+			byte[] buffer = new byte[1024];
+			int len = 0;
+			while ((len = in.read(buffer)) > 0) {
+				out.write(buffer);
+			}
+			in.close();
+			out.close();
+		} catch (FileNotFoundException e) {
+			success = false;
+		} catch (IOException e) {
+			success = false;
+		}
+		return success;
+	}
+
+
+	public static void main(String[] args) {
+		try{
+			String path = "F:\\桌面\\20190925151119-T.h264";
+			FileInputStream f = new FileInputStream(path);
+			fileUpAgain(f, "G:\\javaProject\\9b918c802c3e40282267a89b5231f9a8_201905101446434643\\videos\\", "test123-T.h264", "G:\\javaProject\\9b918c802c3e40282267a89b5231f9a8_201905101446434643\\capture\\");
+//			copyFile(f, "G:\\javaProject\\zhoushan-system\\zhoushan-system-api\\src\\main\\resources\\static\\head", "test.h264");
+		}catch (Exception e){
+			e.printStackTrace();
+		}
+
+	}
+}

+ 240 - 0
4dkankan-utils-file/src/main/java/com/fdkankan/file/utils/FileUtil.java

@@ -0,0 +1,240 @@
+package com.fdkankan.file.utils;
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileChannel.MapMode;
+
+/**
+ * @author MeepoGuan
+ *
+ * <p>Description: file_util</p>
+ *
+ * 2017年4月30日
+ *
+ */
+public class FileUtil {
+
+/*	public static void main(String[] args) {
+		String dirName = "d:/FH/topic/";// 创建目录
+		FileUtil.createDir(dirName);
+	}*/
+
+	/**
+	 * 创建目录
+	 * 
+	 * @param destDirName
+	 *            目标目录名
+	 * @return 目录创建成功返回true,否则返回false
+	 */
+	public static boolean createDir(String destDirName) {
+		File dir = new File(destDirName);
+		if (dir.exists()) {
+			return false;
+		}
+		if (!destDirName.endsWith(File.separator)) {
+			destDirName = destDirName + File.separator;
+		}
+		// 创建单个目录
+		if (dir.mkdirs()) {
+			return true;
+		} else {
+			return false;
+		}
+	}
+
+	/**
+	 * 删除文件
+	 * 
+	 * @param filePathAndName
+	 *            String 文件路径及名称 如c:/fqf.txt
+	 * @return boolean
+	 */
+	public static void delFile(String filePathAndName) {
+		try {
+			String filePath = filePathAndName;
+			filePath = filePath.toString();
+			File myDelFile = new File(filePath);
+			myDelFile.delete();
+
+		} catch (Exception e) {
+			System.out.println("删除文件操作出错");
+			e.printStackTrace();
+
+		}
+
+	}
+
+	/**
+	 * 读取到字节数组0
+	 * 
+	 * @param filePath //路径
+	 * @throws IOException
+	 */
+	public static byte[] getContent(String filePath) throws IOException {
+		File file = new File(filePath);
+		long fileSize = file.length();
+		if (fileSize > Integer.MAX_VALUE) {
+			System.out.println("file too big...");
+			return null;
+		}
+		FileInputStream fi = new FileInputStream(file);
+		byte[] buffer = new byte[(int) fileSize];
+		int offset = 0;
+		int numRead = 0;
+		while (offset < buffer.length
+				&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
+			offset += numRead;
+		}
+		// 确保所有数据均被读取
+		if (offset != buffer.length) {
+			throw new IOException("Could not completely read file "
+					+ file.getName());
+		}
+		fi.close();
+		return buffer;
+	}
+
+	/**
+	 * 读取到字节数组1
+	 * 
+	 * @param filePath
+	 * @return
+	 * @throws IOException
+	 */
+	public static byte[] toByteArray(String filePath) throws IOException {
+
+		File f = new File(filePath);
+		if (!f.exists()) {
+			throw new FileNotFoundException(filePath);
+		}
+		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
+		BufferedInputStream in = null;
+		try {
+			in = new BufferedInputStream(new FileInputStream(f));
+			int buf_size = 1024;
+			byte[] buffer = new byte[buf_size];
+			int len = 0;
+			while (-1 != (len = in.read(buffer, 0, buf_size))) {
+				bos.write(buffer, 0, len);
+			}
+			return bos.toByteArray();
+		} catch (IOException e) {
+			e.printStackTrace();
+			throw e;
+		} finally {
+			try {
+				in.close();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+			bos.close();
+		}
+	}
+
+	/**
+	 * 读取到字节数组2
+	 * 
+	 * @param filePath
+	 * @return
+	 * @throws IOException
+	 */
+	public static byte[] toByteArray2(String filePath) throws IOException {
+
+		File f = new File(filePath);
+		if (!f.exists()) {
+			throw new FileNotFoundException(filePath);
+		}
+
+		FileChannel channel = null;
+		FileInputStream fs = null;
+		try {
+			fs = new FileInputStream(f);
+			channel = fs.getChannel();
+			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
+			while ((channel.read(byteBuffer)) > 0) {
+				// do nothing
+				// System.out.println("reading");
+			}
+			return byteBuffer.array();
+		} catch (IOException e) {
+			e.printStackTrace();
+			throw e;
+		} finally {
+			try {
+				channel.close();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+			try {
+				fs.close();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+	/**
+	 * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
+	 * 
+	 * @param filePath
+	 * @return
+	 * @throws IOException
+	 */
+	public static byte[] toByteArray3(String filePath) throws IOException {
+
+		FileChannel fc = null;
+		RandomAccessFile rf = null;
+		try {
+			rf = new RandomAccessFile(filePath, "r");
+			fc = rf.getChannel();
+			MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
+					fc.size()).load();
+			//System.out.println(byteBuffer.isLoaded());
+			byte[] result = new byte[(int) fc.size()];
+			if (byteBuffer.remaining() > 0) {
+				// System.out.println("remain");
+				byteBuffer.get(result, 0, byteBuffer.remaining());
+			}
+			return result;
+		} catch (IOException e) {
+			e.printStackTrace();
+			throw e;
+		} finally {
+			try {
+				rf.close();
+				fc.close();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+    public static File[] sort(File[] s) {
+        //中间值
+        File temp = null;
+        //外循环:我认为最小的数,从0~长度-1
+        for (int j = 0; j < s.length - 1; j++) {
+            //最小值:假设第一个数就是最小的
+            String min = s[j].getName();
+            //记录最小数的下标的
+            int minIndex = j;
+            //内循环:拿我认为的最小的数和后面的数一个个进行比较
+            for (int k = j + 1; k < s.length; k++) {
+                //找到最小值
+                if (Integer.parseInt(min.substring(0, min.indexOf("."))) > Integer.parseInt(s[k].getName().substring(0, s[k].getName().indexOf(".")))) {
+                    //修改最小
+                    min = s[k].getName();
+                    minIndex = k;
+                }
+            }
+            //当退出内层循环就找到这次的最小值
+            //交换位置
+            temp = s[j];
+            s[j] = s[minIndex];
+            s[minIndex] = temp;
+        }
+        return s;
+    }
+}

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1082 - 0
4dkankan-utils-file/src/main/java/com/fdkankan/file/utils/FileUtils.java


+ 1 - 0
pom.xml

@@ -9,6 +9,7 @@
         <module>4dkankan-utils-db</module>
         <module>4dkankan-utils-redis</module>
         <module>4dkankan-utils-oss</module>
+        <module>4dkankan-utils-file</module>
     </modules>
 
     <groupId>com.fdkankan</groupId>