Environment: SpringBoot2.0
<!-- 七牛 --> <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>[7.2.0, 7.2.99]</version> </dependency>
yml add custom configuration
# Seven cattle configuration
qiniu:
accessKey: xxx
secretKey: yyy
bucketName: bucket1
fileDomain: file.aaa.com # File Access domain name prefix
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 ());. } // covered uplink mode certificate public String getUpToken (String FileKey) { return getAuth () uploadToken (getBucketName (), FileKey);. } / ** * local file Upload * @param filePath local file path * @param FileKeys upload file path name to save after seven cattle * @return * @throws IOException * / public String the Upload (String filePath, String FileKeys) throws IOException { the Response RES; the try { RES =getUploadManager () PUT (filePath, FileKey, getUpToken (FileKey));. // Analytical results of a successful upload DefaultPutRet putRet = new new Gson () fromJson (res.bodyString (), DefaultPutRet.. class ); return fileDomain + "/" + putRet.key; } the catch (QiniuException E) { RES = e.response; e.printStackTrace (); return "upload failed" ; } } / ** * upload binary data * @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); // Analytical results of a successful upload DefaultPutRet putRet = new new Gson () fromJson (res.bodyString (), DefaultPutRet.. Class ); return fileDomain + "/" + putRet.key; } the catch (QiniuException E) { RES = E. the Response; e.printStackTrace (); return "Upload failed" ; } } / ** * delete files * @param FileKeys * @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; } / ** * private space acquired file * @param FileKey * @return * / public String getPrivateFile (String FileKey) throws Exception { String encodedFileName = the URLEncoder.encode (FileKey, "UTF-. 8 ") .replace (" + "," 20 is% " ); String URL = String.format ("% S /% S " , fileDomain, encodedFileName); the Auth the auth = Auth.create (the accessKey, secretKey); Long expireInSeconds = 3600; // 1 hour, you can customize the link expiration time String finalUrl = auth.privateDownloadUrl(url, expireInSeconds); return finalUrl; } }
test
@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 ( "." )); // default without specifying the key, the hash value to the file contents as the file name String fileKey = UUID.randomUUID () . .toString () Replace ( "-", "") + fileExtend; return qiniuUtil.upload (FileInputStream, FileKey); } the catch (Exception E) { e.printStackTrace (); return "upload failed" ; } } }