1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| @Service @Data @ConfigurationProperties(prefix = "oss") public class UploadServiceImpl implements UploadService { private String accessKey; private String secretKey; private String bucket; private String domain;
@Override public String upload(MultipartFile file) { if (file == null){ ApiAsserts.fail("文件上传失败!"); } String originalFileName = file.getOriginalFilename(); assert originalFileName != null; if (!originalFileName.endsWith(".png") && !originalFileName.endsWith(".jpg") && !originalFileName.endsWith(".txt")){ ApiAsserts.fail("只可以上传png格式的图片哦!"); } String path = PathUtils.generateFilePath(originalFileName); return uploadOss(file,path); }
private String uploadOss(MultipartFile file , String path) { Configuration cfg = new Configuration(Region.autoRegion()); UploadManager uploadManager = new UploadManager(cfg); String key = path; try { InputStream inputStream = file.getInputStream(); Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); try { Response response = uploadManager.put(inputStream, key, upToken, null, null); DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); System.out.println(putRet.key); System.out.println(putRet.hash); return domain+key; } catch (QiniuException e) { Response r = e.response; System.err.println(r.toString()); try { System.err.println(r.bodyString()); } catch (QiniuException e2) {
} } } catch (Exception e) {
} return "www"; } }
|