環境:SpringBoot2.0java
<!-- 七牛 --> <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>[7.2.0, 7.2.99]</version> </dependency>
yml增長自定義的配置spring
#七牛的配置
qiniu:
accessKey: xxx
secretKey:yyy
bucketName: bucket1
fileDomain: file.aaa.com #文件訪問域名前綴
import com.google.gson.Gson; import com.qiniu.common.QiniuException; import com.qiniu.common.Zone; import com.qiniu.http.Client; import com.qiniu.http.Response; import com.qiniu.storage.BucketManager; import com.qiniu.storage.Configuration; import com.qiniu.storage.UploadManager; import com.qiniu.storage.model.DefaultPutRet; import com.qiniu.util.Auth; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; @Component public class QiniuUtil { @Value("${qiniu.accessKey}") private String accessKey ; @Value("${qiniu.secretKey}") private String secretKey ; @Value("${qiniu.bucketName}") private String bucketName ; @Value("${qiniu.fileDomain}") private String fileDomain; public String getAccessKey() { return accessKey; } public String getSecretKey() { return secretKey; } public String getBucketName() { return bucketName; } public String getFileDomain() { return fileDomain; } private UploadManager uploadManager; private BucketManager bucketManager; private Configuration c; private Client client; // 密鑰配置 private Auth auth; public Client getClient(){ if (client==null) { client=new Client(getConfiguration()); } return client; } public BucketManager getBucketManager() { if (bucketManager == null) { bucketManager = new BucketManager(getAuth(), getConfiguration()); } return bucketManager; } public UploadManager getUploadManager() { if (uploadManager == null) { uploadManager = new UploadManager(getConfiguration()); } return uploadManager; } public Configuration getConfiguration() { if (c == null) { Zone z = Zone.autoZone(); c = new Configuration(z); } return c; } public Auth getAuth() { if (auth == null) { auth = Auth.create(getAccessKey(), getSecretKey()); } return auth; } //簡單上傳模式的憑證 public String getUpToken() { return getAuth().uploadToken(getBucketName()); } //覆蓋上傳模式的憑證 public String getUpToken(String fileKey) { return getAuth().uploadToken(getBucketName(), fileKey); } /** * 將本地文件上傳 * @param filePath 本地文件路徑 * @param fileKey 上傳到七牛後保存的文件路徑名稱 * @return * @throws IOException */ public String upload(String filePath, String fileKey) throws IOException { Response res; try { res = getUploadManager().put(filePath, fileKey, getUpToken(fileKey)); // 解析上傳成功的結果 DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class); return fileDomain + "/" + putRet.key; } catch (QiniuException e) { res = e.response; e.printStackTrace(); return "上傳失敗"; } } /** * 上傳二進制數據 * @param data * @param fileKey * @return * @throws IOException */ public String upload(byte[] data, String fileKey) throws IOException { Response res; try { res = getUploadManager().put(data, fileKey, getUpToken(fileKey)); // 解析上傳成功的結果 DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class); return fileDomain + "/" + putRet.key; } catch (QiniuException e) { res = e.response; e.printStackTrace(); return "上傳失敗"; } } /** * 上傳輸入流 * @param inputStream * @param fileKey * @return * @throws IOException */ public String upload(InputStream inputStream, String fileKey) throws IOException { Response res; try { res = getUploadManager().put(inputStream, fileKey, getUpToken(fileKey),null,null); // 解析上傳成功的結果 DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class); return fileDomain + "/" + putRet.key; } catch (QiniuException e) { res = e.response; e.printStackTrace(); return "上傳失敗"; } } /** * 刪除文件 * @param fileKey * @return * @throws QiniuException */ public boolean delete(String fileKey) throws QiniuException { Response response = bucketManager.delete(this.getBucketName(), fileKey); return response.statusCode == 200 ? true:false; } /** * 獲取公共空間文件 * @param fileKey * @return */ public String getFile(String fileKey) throws Exception{ String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20"); String url = String.format("%s/%s", fileDomain, encodedFileName); return url; } /** * 獲取私有空間文件 * @param fileKey * @return */ public String getPrivateFile(String fileKey) throws Exception{ String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20"); String url = String.format("%s/%s", fileDomain, encodedFileName); Auth auth = Auth.create(accessKey, secretKey); long expireInSeconds = 3600;//1小時,能夠自定義連接過時時間 String finalUrl = auth.privateDownloadUrl(url, expireInSeconds); return finalUrl; } }
測試app
@RestController @RequestMapping("/qiniuTest") public class QiNiuTestController { @Autowired private QiniuUtil qiniuUtil; @RequestMapping("/upload") @ResponseBody public String upload(@RequestParam("file1") MultipartFile file) { if (file.isEmpty()) { return "請選擇文件"; } try { FileInputStream fileInputStream = (FileInputStream) file.getInputStream(); String originalFilename = file.getOriginalFilename(); String fileExtend = originalFilename.substring(originalFilename.lastIndexOf(".")); //默認不指定key的狀況下,以文件內容的hash值做爲文件名 String fileKey = UUID.randomUUID().toString().replace("-", "") + fileExtend; return qiniuUtil.upload(fileInputStream,fileKey); } catch (Exception e) { e.printStackTrace(); return "上傳失敗"; } } }