danchaofan1412 преди 5 години
родител
ревизия
8c1a3faf19

+ 13 - 0
framework-common/pom.xml

@@ -7,6 +7,19 @@
     <groupId>com.mrxu</groupId>
     <artifactId>framework-common</artifactId>
     <version>1.0-SNAPSHOT</version>
+    <dependencies>
+
+        <dependency>
+            <groupId>com.qiniu</groupId>
+            <artifactId>qiniu-java-sdk</artifactId>
+            <version>7.0.11</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+        </dependency>
+    </dependencies>
     <packaging>jar</packaging>
     <name>framework-common</name>
     <description>工具类</description>

+ 223 - 0
framework-common/src/main/java/com/mrxu/framework/common/util/FileFunc.java

@@ -0,0 +1,223 @@
+package com.mrxu.framework.common.util;
+
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+
+public class FileFunc {
+	
+	/**
+	 * 文件里面写内容
+	 * @param filePath
+	 * @param fileName
+	 * @param sb
+	 * @param isadd
+	 */
+	public static void write(String filePath,String fileName,String sb,boolean isadd) {
+		File fp = new File(filePath);  
+		if (!fp.exists()) {
+			fp.mkdirs();//目录不存在的情况下,创建目录。
+		}
+		FileWriter writer = null;
+		try {
+			writer = new FileWriter(filePath+fileName,isadd);
+			writer.write(sb.toString()); 
+	        
+		}
+		catch (Exception e) {
+			e.printStackTrace();
+		}
+		finally {
+			try {
+				if(writer != null) {
+					writer.close();
+				}
+			}
+			catch (IOException e) {
+				e.printStackTrace();
+			} 
+		}
+        
+	}
+	
+	public static byte[] getBytes(String filePath) {
+		byte[] buffer = null;
+		try {
+			File file = new File(filePath);
+			FileInputStream fis = new FileInputStream(file);
+			ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
+			byte[] b = new byte[1024];
+			int n;
+			while ((n = fis.read(b)) != -1) {
+				bos.write(b, 0, n);
+			}
+			fis.close();
+			bos.close();
+			buffer = bos.toByteArray();
+		}
+		catch (FileNotFoundException e) {
+			e.printStackTrace();
+		}
+		catch (IOException e) {
+			e.printStackTrace();
+		}
+		return buffer;
+	}
+
+	/**
+	 * 根据byte数组,生成文件
+	 */
+	public static void saveFile(byte[] bfile, String filePath, String fileName) {
+		BufferedOutputStream bos = null;
+		FileOutputStream fos = null;
+		File file = null;
+		try {
+			File dir = new File(filePath);
+			if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
+				dir.mkdirs();
+			}
+			file = new File(filePath + "\\" + fileName);
+			fos = new FileOutputStream(file);
+			bos = new BufferedOutputStream(fos);
+			bos.write(bfile);
+		}
+		catch (Exception e) {
+			e.printStackTrace();
+		}
+		finally {
+			if (bos != null) {
+				try {
+					bos.close();
+				}
+				catch (IOException e1) {
+					e1.printStackTrace();
+				}
+			}
+			if (fos != null) {
+				try {
+					fos.close();
+				}
+				catch (IOException e1) {
+					e1.printStackTrace();
+				}
+			}
+		}
+	}
+
+	/**
+	 * 获取文件后缀名
+	 * @param file
+	 * @return
+	 */
+	public static String getFileType(File file) {
+		String name = file.getName();
+		return name.substring(name.lastIndexOf(".")+1);
+	}
+
+	/**
+	 * 下载网络文件,用U拍云图片下载
+	 */
+	public static File download(String urlString,String path) {
+		File outFile = new File(path);
+		if(!outFile.exists()) {
+			try {
+				outFile.createNewFile();
+			} catch (IOException e1) {
+				// TODO Auto-generated catch block
+				e1.printStackTrace();
+			}
+		}
+
+		URL url = null;
+		OutputStream os = null;
+		InputStream is = null;
+		try {
+			url = new URL(urlString);
+			os = new FileOutputStream(outFile);
+			is = url.openStream();
+			byte[] buff = new byte[1024];
+			while (true) {
+				int count = is.read(buff);
+				if (count == -1) {
+					break;
+				}
+				os.write(buff, 0, count);
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			if (is != null) {
+				try {
+					is.close();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+			}
+			if (os != null) {
+				try {
+					os.close();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+			}
+		}
+		return outFile;
+	}
+
+	public static String uploadFile(String urlStr,String type,File file) {
+		String res = "";
+		HttpURLConnection conn = null;
+		String BOUNDARY = "---------------------------123821742118716";
+		try {
+			URL url = new URL(urlStr);
+			conn = (HttpURLConnection) url.openConnection();
+			conn.setConnectTimeout(5000);
+			conn.setReadTimeout(30000);
+			conn.setDoOutput(true);
+			conn.setDoInput(true);
+			conn.setUseCaches(false);
+			conn.setRequestMethod("POST");
+			conn.setRequestProperty("Connection", "Keep-Alive");
+			conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
+			conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
+			OutputStream out = new DataOutputStream(conn.getOutputStream());
+			StringBuffer strBuf = new StringBuffer();
+			strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
+			strBuf.append("Content-Disposition: form-data;name=\"media\";filename=\"example.png\"\r\n");
+			strBuf.append("Content-Type:application/octet-stream\r\n\r\n");
+			out.write(strBuf.toString().getBytes());
+			int bytes = 0;
+			byte[] bufferOut = new byte[1024];
+			FileInputStream in = new FileInputStream(file);
+			while ((bytes = in.read(bufferOut)) != -1) {
+				out.write(bufferOut, 0, bytes);
+			}
+			in.close();
+			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
+			out.write(endData);
+			out.flush();
+			out.close();
+			// 读取返回数据
+			StringBuffer rs = new StringBuffer();
+			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
+			String line = null;
+			while ((line = reader.readLine()) != null) {
+				rs.append(line).append("\n");
+			}
+			res = rs.toString();
+			reader.close();
+			reader = null;
+		}
+		catch (Exception e) {
+			e.printStackTrace();
+		}
+		finally {
+			if (conn != null) {
+				conn.disconnect();
+				conn = null;
+			}
+		}
+		return res;
+	}
+}

+ 173 - 0
framework-common/src/main/java/com/mrxu/framework/common/util/QiniuService.java

@@ -0,0 +1,173 @@
+package com.mrxu.framework.common.util;
+
+import com.alibaba.fastjson.JSONObject;
+import com.qiniu.common.QiniuException;
+import com.qiniu.http.Response;
+import com.qiniu.storage.BucketManager;
+import com.qiniu.storage.UploadManager;
+import com.qiniu.util.Auth;
+
+import java.io.File;
+
+
+
+
+public class QiniuService {
+
+    //public static String url = "http://og2n7jbwn.bkt.clouddn.com";
+    public static String url = "http://codeyn.com";
+
+    public static String accessKey = "3B1iwJIXyqNap2bOCd90GhI8giR48e79DFxRwG8k";
+
+    public static String secretKey = "oTLVDEVzo7XU1hjdRqnF6vCSKScFL2v7qBx1kwJK";
+
+    public static String bucket = "xu-res";
+
+    private static Auth auth = null;
+
+    private static BucketManager bucketManager = null;
+
+    /**
+     * 上传所需要的工具类
+     */
+    public static UploadManager uploadManager = new UploadManager();
+
+
+    public static String upload(byte[] data) {
+        try {
+            String fileName = StrFunc.randomString(32)+".jpg";
+            Response res = uploadManager.put(data,fileName, getUpToken());
+            if(res.isOK()) {
+                JSONObject json = (JSONObject) JSONObject.parse(res.bodyString());
+                return url+"/"+json.getString("key");
+            }
+            else {
+                throw new RuntimeException(res.error);
+            }
+        }
+        catch (QiniuException e) {
+            e.printStackTrace();
+            throw new RuntimeException(e.getMessage());
+        }
+    }
+
+    /**
+     * 文件上传接口
+     * @param file
+     * @return
+     */
+    public static String upload(File file,String fileName) {
+        try {
+            if(StrFunc.isEmpty(fileName)) {
+                fileName = StrFunc.randomString(32)+"."+FileFunc.getFileType(file);
+            }
+            Response res = uploadManager.put(file,fileName, getUpToken());
+            if(res.isOK()) {
+                JSONObject json = (JSONObject) JSONObject.parse(res.bodyString());
+                return url+"/"+json.getString("key");
+            }
+            else {
+                throw new RuntimeException(res.error);
+            }
+        }
+        catch (QiniuException e) {
+            e.printStackTrace();
+            throw new RuntimeException(e.getMessage());
+        }
+    }
+
+    /**
+     * 文件上传接口
+     * @param data
+     * @return
+     */
+    public static String upload(byte[] data,String fileName) {
+        try {
+            Response res = uploadManager.put(data,fileName, getUpToken());
+            if(res.isOK()) {
+                JSONObject json = (JSONObject) JSONObject.parse(res.bodyString());
+                return json.getString("key");
+            }
+            else {
+                throw new RuntimeException(res.error);
+            }
+        }
+        catch (QiniuException e) {
+            throw new RuntimeException(e.getMessage());
+        }
+    }
+
+    /**
+     * 删除文件
+     * @param key
+     */
+    public static void delete(String key) {
+        try {
+            getBucketManager().delete(bucket, key);
+        }
+        catch (QiniuException e) {
+            Response res = e.response;
+            if(res.statusCode == 612) {
+                //todo  log
+                System.out.println("该文件不存在,可能已经被删除!");
+            }
+            else {
+                throw new RuntimeException(e.getMessage());
+            }
+        }
+    }
+
+    private static String getUpToken() {
+        return getAuth().uploadToken(bucket);
+    }
+
+    private static Auth getAuth() {
+        if(auth == null) {
+            auth = Auth.create(accessKey, secretKey);
+        }
+        return auth;
+    }
+
+    private static BucketManager getBucketManager() {
+        if(bucketManager == null) {
+            bucketManager = new BucketManager(getAuth());
+
+        }
+        return bucketManager;
+    }
+
+    public static void main(String[] args) {
+        //File file = new File("d://222.jpg");
+        //getFiles("D:\\code\\mrxu-res\\src\\main\\webapp\\res\\haotianlai\\res");
+        //System.out.println(upload(file,null));
+        getFile(new File("D:\\test\\mrxu-res\\src\\main\\webapp\\res\\easyweb\\assets\\module\\iconPicker.js"));
+        System.out.println("执行完成!");
+    }
+
+
+    public static void getFiles(String filePath) {
+        File root = new File(filePath);
+        File[] files = root.listFiles();
+        for (File file : files) {
+            if (file.isDirectory()) {
+                getFiles(file.getAbsolutePath());
+            }
+            else {
+                getFile(file);
+            }
+        }
+    }
+
+    public static void getFile(File file) {
+        String fileName = file.getAbsolutePath();
+        int index = fileName.indexOf("\\webapp\\res\\");
+        fileName = "V1/"+fileName.substring(index+8, fileName.length()).replaceAll("\\\\", "/");
+        //TODO delete
+        //fileName = fileName.replace("V1/res/panh/", "");
+        delete(fileName);
+        upload(file,fileName);
+        System.out.println(url+"/"+fileName);
+    }
+
+}
+

+ 31 - 0
framework-common/src/main/java/com/mrxu/framework/common/util/StrFunc.java

@@ -1,5 +1,6 @@
 package com.mrxu.framework.common.util;
 
+import java.util.Random;
 import java.util.UUID;
 
 public class StrFunc {
@@ -90,4 +91,34 @@ public class StrFunc {
         return UUID.randomUUID().toString();
     }
 
+    private static char[] org  = ("0123456789abcdefghijklmnopqrstuvwxyz" +
+            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
+    private static char[] numOrg  = ("0123456789").toCharArray();
+    public static String randomString(int length) {
+        Random randGen  = new Random();
+
+        int orgLeng=org.length;
+        if (length < 1) {
+            return null;
+        }
+        char [] randBuffer = new char[length];
+        for (int i=0; i<length; i++) {
+            randBuffer[i] = org[randGen.nextInt(orgLeng)];
+        }
+        return new String(randBuffer);
+    }
+
+    public static String randomNumber(int length) {
+        Random randGen  = new Random();
+        int orgLeng = numOrg.length;
+        if (length < 1) {
+            return null;
+        }
+        char [] randBuffer = new char[length];
+        for (int i=0; i<length; i++) {
+            randBuffer[i] = org[randGen.nextInt(orgLeng)];
+        }
+        return new String(randBuffer);
+    }
+
 }