Java七牛クラウドファイルアップロード(リモートサーバ)
3447 ワード
pom.xmlの導入
QiniuController.java
QiniuUtil.java
com.qiniu
qiniu-java-sdk
7.2.0
QiniuController.java
import com.education.ak1.utils.QiNiuUtil;
import com.qiniu.common.QiniuException;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/upload")
public class QiniuController {
@PostMapping("/file")
@ApiOperation(value = " ", notes = " ")
public Object upload(@RequestParam(value = "file", required = false) MultipartFile file){
Map map = new HashMap<>();
try {
InputStream is = file.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = -1;
while ((len = is.read(b)) != -1) {
bos.write(b, 0, len);
}
byte[] uploadBytes = bos.toByteArray();
String url = QiNiuUtil.upload(uploadBytes);
map.put("code", 0);
map.put("msg", " !");
map.put("data", url);
}catch (QiniuException e){
map.put("code", 4001);
map.put("msg", " !");
map.put("data", "");
}catch (IOException e){
map.put("code", 4001);
map.put("msg", " !");
map.put("data", "");
}
return map;
}
}
QiniuUtil.java
import com.education.ak1.contant.QiNiuContant;
import com.google.gson.Gson;
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.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import java.util.UUID;
public class QiNiuUtil {
public static String getUpToken() {
Auth auth = Auth.create(QiNiuContant.AccessKey, QiNiuContant.SecretKey);
String uptoken = auth.uploadToken(QiNiuContant.bucketName);
return uptoken;
}
public static String upload(byte[] uploadBytes) throws QiniuException{
String key = UUID.randomUUID().toString().replaceAll("-", "");
Configuration cfg = new Configuration(Zone.zone2());//
UploadManager uploadManager = new UploadManager(cfg);
String upToken = getUpToken();
Response response = uploadManager.put(uploadBytes, key, upToken);
//
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
String urlPath = QiNiuContant.MediaUrl + putRet.key;
return urlPath;
}
}