utils
package com.example.demo.utils;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
/**
* @Author:lgl
* @Description:
* @Date:Create in 2018/3/9 .
*/
public class UploadImages {
private static final Logger LOG = LogManager.getLogger("UploadArticle");
public static final String ak = "***";
public static final String sk = "***";
public static final String bucket = "images"; //正式环境
static Auth auth = Auth.create(ak, sk);
/* 上传至 华东 */
static Zone z = Zone.zone0();
static Configuration c = new Configuration(z);
// 创建上传对象
static UploadManager uploadManager = new UploadManager(c);
private static String QINIU_IMAGE_DOMAIN= "***";
public static String getUpToken() {
return auth.uploadToken(bucket);
}
public static String saveImage(MultipartFile file)throws IOException {
String pic_type = file.getContentType();
if (pic_type.equals("image/jpeg") || pic_type.equals("image/png") || pic_type.equals("image/bmp")
|| pic_type.equals("image/gif")) {
try {
String fileEnd = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + fileEnd;
//调用put方法上传
Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
//打印返回的信息
if (res.isOK() && res.isJson()) {
return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
} else {
LOG.error("七牛异常1:" + res.bodyString());
return null;
}
} catch (QiniuException e) {
// 请求失败时打印的异常的信息
Response r = e.response;
System.out.println(r.toString());
LOG.error("七牛异常2:" + e.getMessage());
return null;
}
}else{
return "非图片";
}
}
}
jar
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.17</version>
</dependency>