一、需要的几个配置数据
二、如何在七牛云获取这几个参数
七牛云地址:https://s.qiniu.com/uI73yi
不需要花钱,注册登录送永久的10个g内存空间
三、在springboot测试、使用
1、依赖
<!--七牛云-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.7.99]</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>happy-dns-java</artifactId>
<version>0.1.6</version>
<scope>test</scope>
</dependency>
2、代码
//处理文件上传
@Log("文件上传")
@RequestMapping(value = "uploadImg", method = RequestMethod.POST)
public R uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws JSONException {
String contentType = file.getContentType();
//System.out.print(contentType);
String fileName = System.currentTimeMillis()+file.getOriginalFilename();
int code = 0;
String filePath = "D:/E";
//JSONObject jo = new JSONObject();//实例化json数据
//Map<String,String> jo = new HashMap<>();
if (file.isEmpty()) {
code = 1;
fileName = "";
}
try {
uploadFile(file.getBytes(), filePath, fileName);
code = 0;
} catch (Exception e) {
// TODO: handle exception
}
//返回json
return R.ok().put("code",code).put("filename","/imctemp-rainy/"+fileName);
}
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
out.write(file);
out.flush();
out.close();
Configuration cfg = new Configuration(Zone.zone1()); // zong1() 代表华北地区
UploadManager uploadManager = new UploadManager(cfg);
String accessKey = "这里写自己的"; // AccessKey的值
String secretKey = "这里写自己的"; // SecretKey的值
String bucket = "这里写自己的"; // 存储空间名
String localFilePath = filePath +"/"+ fileName; // 上传图片路径
String key = fileName; // 在七牛云中图片的命名
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);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
// ignore
}
}
}