工具类-三方工具的使用

七牛云

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
@Slf4j
public class QiniuUtil {

/**
* 生成上传凭证,然后准备上传
*/
private static String accessKey = "你的accessKey";
private static String secretKey = "你的secretKey";
private static String bucket = "你的空间名,例如xmall";
private static String origin="你的域名,例如http://pbsw9oba0.bkt.clouddn.com/";
private static Auth auth = Auth.create(accessKey, secretKey);

public static String getUpToken() {
return auth.uploadToken(bucket, null, 3600, new StringMap().put("insertOnly", 1));
}

public static String qiniuUpload(String filePath){

//构造一个带指定Zone对象的配置类 zone2华南
Configuration cfg = new Configuration(Zone.zone2());
UploadManager uploadManager = new UploadManager(cfg);

String localFilePath = filePath;
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(localFilePath, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return origin+putRet.key;
}catch(QiniuException ex){
Response r = ex.response;
log.warn(r.toString());
try {
return r.bodyString();
} catch (QiniuException e) {
throw new XmallUploadException(e.toString());
}
}
}

/**
* 文件流上传
* @param file
* @param key 文件名
* @return
*/
public static String qiniuInputStreamUpload(FileInputStream file, String key){

//构造一个带指定Zone对象的配置类 zone2华南
Configuration cfg = new Configuration(Zone.zone2());
UploadManager uploadManager = new UploadManager(cfg);

Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(file,key,upToken,null, null);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return origin+putRet.key;
} catch (QiniuException ex) {
Response r = ex.response;
log.warn(r.toString());
try {
return r.bodyString();
} catch (QiniuException e) {
throw new XmallUploadException(e.toString());
}
}
}

public static String qiniuBase64Upload(String data64){

String key = renamePic(".png");
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
//服务端http://up-z2.qiniup.com
String url = "http://up-z2.qiniup.com/putb64/-1/key/"+ UrlSafeBase64.encodeToString(key);
RequestBody rb = RequestBody.create(null, data64);
Request request = new Request.Builder().
url(url).
addHeader("Content-Type", "application/octet-stream")
.addHeader("Authorization", "UpToken " + getUpToken())
.post(rb).build();
OkHttpClient client = new OkHttpClient();
okhttp3.Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
return origin+key;
}

public static String base64Data(String data){
if(data==null||data.isEmpty()){
return "";
}
String base64 =data.substring(data.lastIndexOf(",")+1);
return base64;
}

/**
* 以UUID重命名
* @param fileName
* @return
*/
public static String renamePic(String fileName){
String extName = fileName.substring(fileName.lastIndexOf("."));
return UUID.randomUUID().toString().replace("-","")+extName;
}

public static String isValidImage(HttpServletRequest request, MultipartFile file){
//最大文件大小
long maxSize = 5242880;
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");

if(!ServletFileUpload.isMultipartContent(request)){
return "请选择文件";
}

if(file.getSize() > maxSize){
return "上传文件大小超过5MB限制";
}
//检查扩展名
String fileName=file.getOriginalFilename();
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
return "上传文件扩展名是不允许的扩展名\n只允许" + extMap.get("image") + "格式";
}

return "valid";
}

public static String checkExt(String fileName,String dirName){
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");

//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
return "上传文件扩展名是不允许的扩展名\n只允许" + extMap.get(dirName) + "格式";
}
return "valid";
}

public static void main(String[] args){
base64Data("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2");
}
}

方法调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@RestController
@Api(description = "图片上传统一接口")
public class ImageController {

@RequestMapping(value = "/image/imageUpload",method = RequestMethod.POST)
@ApiOperation(value = "WebUploader图片上传")
public Result<Object> uploadFile(@RequestParam("file") MultipartFile files,
HttpServletRequest request){

String imagePath=null;
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/upload")+"\\"
+ QiniuUtil.renamePic(files.getOriginalFilename());
// 转存文件
try {
//保存至服务器
File file=new File((filePath));
files.transferTo(file);
//上传七牛云服务器
imagePath= QiniuUtil.qiniuUpload(filePath);
if(imagePath.contains("error")){
throw new XmallUploadException("上传失败");
}
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
return new ResultUtil<Object>().setData(imagePath);
}

@RequestMapping(value = "/kindeditor/imageUpload",method = RequestMethod.POST)
@ApiOperation(value = "KindEditor图片上传")
public KindEditorResult kindeditor(@RequestParam("imgFile") MultipartFile files, HttpServletRequest request){

KindEditorResult kindEditorResult=new KindEditorResult();
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/upload")+"\\"
+ QiniuUtil.renamePic(files.getOriginalFilename());
//检查文件
String message=QiniuUtil.isValidImage(request,files);
if(!message.equals("valid")){
kindEditorResult.setError(1);
kindEditorResult.setMessage(message);
return kindEditorResult;
}
// 转存文件
try {
//保存至服务器
File file=new File((filePath));
files.transferTo(file);
//上传七牛云服务器
String imagePath=QiniuUtil.qiniuUpload(filePath);
if(imagePath.contains("error")){
kindEditorResult.setError(1);
kindEditorResult.setMessage("上传失败");
return kindEditorResult;
}
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
}
kindEditorResult.setError(0);
kindEditorResult.setUrl(imagePath);
return kindEditorResult;
} catch (IOException e) {
e.printStackTrace();
}
kindEditorResult.setError(1);
kindEditorResult.setMessage("上传失败");
return kindEditorResult;
}

天气

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
public class IPInfoUtil {

private static final Logger log = LoggerFactory.getLogger(IPInfoUtil.class);

/**
* Mob官网注册申请即可
*/
private final static String APPKEY = "你的APPKEY";
/**
* Mob全国天气预报接口
*/
private final static String GET_WEATHER="http://apicloud.mob.com/v1/weather/ip?key="+ APPKEY +"&ip=";

/**
* 获取客户端IP地址
* @param request 请求
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if (ip.equals("127.0.0.1")) {
//根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ip = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ip != null && ip.length() > 15) {
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}

/**
* 获取IP返回地理天气信息
* @param ip ip地址
* @return
*/
public static String getIpInfo(String ip){
if(null != ip){
String url = GET_WEATHER + ip;
String result= HttpUtil.sendGet(url);
return result;
}
return null;
}

/**
* 获取IP返回地理信息
* @param ip ip地址
* @return
*/
public static String getIpCity(String ip){
if(null != ip){
String url = GET_WEATHER + ip;
String json= HttpUtil.sendGet(url);
String result="未知";
try{
IpWeatherResult weather=new Gson().fromJson(json,IpWeatherResult.class);
result=weather.getResult().get(0).getCity()+" "+weather.getResult().get(0).getDistrct();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
return null;
}

public static void getInfo(HttpServletRequest request, String p){
try {
IpInfo info = new IpInfo();
info.setUrl(request.getRequestURL().toString());
info.setP(p);
String result = HttpRequest.post("https://api.bmob.cn/1/classes/url")
.header("X-Bmob-Application-Id", "46970b236e5feb2d9c843dce2b97f587")
.header("X-Bmob-REST-API-Key", "171674600ca49e62e0c7a2eafde7d0a4")
.header("Content-Type", "application/json")
.body(new Gson().toJson(info, IpInfo.class))
.execute().body();
}catch (Exception e){
e.printStackTrace();
}
}

public static void main(String[] args){
log.info(getIpInfo("IP测试"));
}

阿里云OSS

阿里云为了安全起见,采取了生成STS账户的规范,用于零时读取文件和获取资源。

1、添加依赖:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-sts</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.5.0</version>
</dependency>

2、STS账户的创建:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class StsUtil {
public static void main(String[] args) {
String endpoint = "sts.aliyuncs.com";
//这里的accessKeyId和accessKeySecret为STS账户
String accessKeyId = "LTAIZRKdWYalIfQ1";
String accessKeySecret = "UVBjexBMsHuLuVGqfC12fWgse0NVaw";
//对应RAM角色
String roleArn = "acs:ram::1599992521629183:role/aliyunosstokengeneratorrole";
String roleSessionName = "external-username";
//language=JSON
String policy = "{\n" +
" \"Version\": \"1\",\n" +
" \"Statement\": [\n" +
" {\n" +
" \"Effect\": \"Allow\",\n" +
" \"Action\": [\n" +
" \"oss:*\"\n" +
" ],\n" +
" \"Resource\": [\n" +
" \"acs:oss:*:*:oss-test-jwt\",\n" +
" \"acs:oss:*:*:oss-test-jwt/*\"\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
try {
// 添加endpoint(直接使用STS endpoint,前两个参数留空,无需添加region ID)
DefaultProfile.addEndpoint("", "", "Sts", endpoint);
// 构造default profile(参数留空,无需添加region ID)
IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
// 用profile构造client
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
request.setPolicy(policy); // Optional
final AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println("Expiration: " + response.getCredentials().getExpiration());
System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
System.out.println("RequestId: " + response.getRequestId());
System.out.println("Token size: " + response.getCredentials().getSecurityToken().length());
} catch (ClientException e) {
System.out.println("Failed:");
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMsg());
System.out.println("RequestId: " + e.getRequestId());
}
}
}

3、核心业务逻辑(上传/下载):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

//阿里云API的内或外网域名,STS账户生成的随机账户、密码和token
private static String ENDPOINT="http://oss-cn-shanghai.aliyuncs.com";
private static String ACCESS_KEY_ID = "STS.NHxd2pz8xKH79Dsrdey3hUHEt";
private static String ACCESS_KEY_SECRET = "...";
private static String SECURITY_TOKEN = "....";

public static boolean upload2OSS(MultipartFile file, String bucketName, String diskName) {
// 1、创建client
OSS oss_client = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
try {
// 2、创建上传Object的Metadata
ObjectMetadata metadata = new ObjectMetadata();
metadata.setCacheControl("no-cache");
metadata.setContentEncoding("utf-8");
metadata.setHeader("x-oss-security-token", evidenceOssFileDto.getSecurityToken());
metadata.setExpirationTime(evidenceOssFileDto.getExpirationDate());
metadata.setContentType(getContentType(fileName));
metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
// 3、设置MD5校验(重要,此处必须使用64位MD5)
String ali_md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(data));
metadata.setContentMD5(ali_md5);
// 4、上传文件
// PutObjectResult putResult = client.putObject(bucketName, diskName, new ByteArrayInputStream(byte[] data), metadata);
PutObjectResult putResult = client.putObject(bucketName, diskName, file.getInputStream(), metadata);

//解析结果
if(putResult.getETag()!=null){
return true;
}
return false;
} catch (Exception e) {
log.error("上传阿里云OSS服务器异常." + e.getMessage());
return false;
}finally {
client.shutdown();
}


private static final String getContentType(String fileName){
String fileExtension = fileName.substring(fileName.lastIndexOf(".")+1);
if("bmp".equalsIgnoreCase(fileExtension)) {
return "image/bmp";
}
if("gif".equalsIgnoreCase(fileExtension)) {
return "image/gif";
}
if("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension) || "png".equalsIgnoreCase(fileExtension) ) {
return "image/jpeg";
}
if("html".equalsIgnoreCase(fileExtension)) {
return "text/html";
}
if("txt".equalsIgnoreCase(fileExtension)) {
return "text/plain";
}
if("vsd".equalsIgnoreCase(fileExtension)) {
return "application/vnd.visio";
}
if("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
return "application/vnd.ms-powerpoint";
}
if("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
return "application/msword";
}
if("xml".equalsIgnoreCase(fileExtension)) {
return "text/xml";
}
return "text/html";
}

4、调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
@PostMapping("/testUpload")
public boolean testUpload(@RequestBody MultipartFile file){

String bucketName= "oss-test-jwt";
String diskName= "paasTestEvidence1/201905090905/0.jpg";
boolean res;
try {
res = OSSUtil.upload2OSS(file,bucketName,diskName);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
文章作者: gqsu
文章链接: http://www.ipdax.com/2018/10/08/util-工具类-三方工具的使用/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 技术笔记分享
支付宝打赏
微信打赏