前提:
获取到阿里云账号的AccessKey ID 和AccessKey Secret:
操作步骤:
1.添加Pom依赖
<dependency><groupId>com.aliyun</groupId><artifactId>tea-openapi</artifactId><version>0.0.7</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>openplatform20191219</artifactId><version>3.0.1</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>oss-client</artifactId><version>3.0.2</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.7</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.5.13</version></dependency>
2.Code Sample
importcom.aliyun.fileform.models.FileField; importcom.aliyun.openplatform20191219.models.AuthorizeFileUploadRequest; importcom.aliyun.openplatform20191219.models.AuthorizeFileUploadResponse; importcom.aliyun.oss.models.PostObjectRequest; importcom.aliyun.tea.TeaConverter; importcom.aliyun.tea.TeaPair; importcom.aliyun.teautil.models.RuntimeOptions; importorg.apache.commons.lang3.StringUtils; importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.InputStream; importjava.net.URL; importjava.net.URLConnection; importjava.net.URLDecoder; importjava.util.HashMap; importjava.util.Map; importjava.util.concurrent.ConcurrentHashMap; // 使用Java SDK通过本地文件或网络文件链接生成URLpublicclassViapiFileUtilAdvance { publicstaticvoidmain(String[] args) throwsException { StringaccessKey="xxxxxxxxxx"; //您的AccessKeyIDStringaccessKeySecret="xxxxxxxxxx"; //您的AccessKeySecretStringregionId="cn-shanghai"; Stringfile="D:/picture/recognize_1.jpg"; //或者本地上传//String file = "https://img.alicdn.com/tfs/TB1S0DjC4v1gK0jSZFFXXb0sXXa-692-440.jpg";try (InputStreaminputStream=buildInputStream(file)) { ViapiFileUtilAdvancefileUtils=ViapiFileUtilAdvance.getInstance(accessKey, accessKeySecret, regionId); StringossTempFileUrl=fileUtils.upload(inputStream); System.out.println(ossTempFileUrl); } } publicstaticInputStreambuildInputStream(StringfilePath) throwsIOException { if (StringUtils.startsWithAny(filePath, newCharSequence[]{"http://", "https://"})) { filePath=URLDecoder.decode(filePath, "UTF-8"); URLurl=newURL(filePath); URLConnectionurlConnection=url.openConnection(); returnurlConnection.getInputStream(); } else { Filekey1=newFile(filePath); returnnewFileInputStream(key1); } } publicstaticsynchronizedViapiFileUtilAdvancegetInstance(StringaccessKeyId, StringaccessKeySecret, StringregionId) throwsException { StringmapKey=String.format("%s:%s:%s", regionId, accessKeyId, accessKeySecret); ViapiFileUtilAdvancefileUtils=_map.get(mapKey); if (fileUtils==null) { _map.putIfAbsent(mapKey, newViapiFileUtilAdvance(accessKeyId, accessKeySecret, regionId)); fileUtils=_map.get(mapKey); } returnfileUtils; } privateViapiFileUtilAdvance(StringaccessKeyId, StringaccessKeySecret, StringregionId) throwsException { Map<String, Object>cm=newHashMap<>(); cm.put("regionId", regionId); cm.put("autoretry", "true"); cm.put("accessKeyId", accessKeyId); cm.put("accessKeySecret", accessKeySecret); cm.put("connectTimeout", 15*1000); cm.put("readTimeout", 30*1000); cm.put("maxIdleConns", 200); cm.put("type", "access_key"); cm.put("endpoint", "openplatform.aliyuncs.com"); _runtime=RuntimeOptions.build(cm); com.aliyun.tearpc.models.ConfigauthConfig=com.aliyun.tearpc.models.Config.build(cm); _authClient=newcom.aliyun.openplatform20191219.Client(authConfig); //ossEndpointType = "internal";//aliyun-vpc_ossConfig=com.aliyun.oss.models.Config.build(TeaConverter.buildMap( newTeaPair("accessKeySecret", accessKeySecret), newTeaPair("type", "access_key"), newTeaPair("protocol", _authClient._protocol), newTeaPair("regionId", _authClient._regionId) )); } publicStringupload(InputStreaminputStream) throwsException { AuthorizeFileUploadRequestauthRequest=AuthorizeFileUploadRequest.build(TeaConverter.buildMap( newTeaPair("product", "imageseg"), newTeaPair("regionId", _authClient._regionId) )); AuthorizeFileUploadResponseauthResponse=_authClient.authorizeFileUploadWithOptions(authRequest, _runtime); com.aliyun.oss.models.ConfigossConfig=newcom.aliyun.oss.models.Config(); com.aliyun.openapiutil.Client.convert(_ossConfig, ossConfig); ossConfig.accessKeyId=authResponse.accessKeyId; ossConfig.endpoint=com.aliyun.openapiutil.Client.getEndpoint(authResponse.endpoint, authResponse.useAccelerate, ossEndpointType); com.aliyun.oss.ClientossClient=newcom.aliyun.oss.Client(ossConfig); FileFieldfileObj=FileField.build(TeaConverter.buildMap( newTeaPair("filename", authResponse.objectKey), newTeaPair("content", inputStream), newTeaPair("contentType", "") )); PostObjectRequest.PostObjectRequestHeaderossHeader=PostObjectRequest.PostObjectRequestHeader.build(TeaConverter.buildMap( newTeaPair("accessKeyId", authResponse.accessKeyId), newTeaPair("policy", authResponse.encodedPolicy), newTeaPair("signature", authResponse.signature), newTeaPair("key", authResponse.objectKey), newTeaPair("file", fileObj), newTeaPair("successActionStatus", "201") )); PostObjectRequestuploadRequest=PostObjectRequest.build(TeaConverter.buildMap( newTeaPair("bucketName", authResponse.bucket), newTeaPair("header", ossHeader) )); com.aliyun.ossutil.models.RuntimeOptionsossRuntime=newcom.aliyun.ossutil.models.RuntimeOptions(); com.aliyun.openapiutil.Client.convert(_runtime, ossRuntime); ossClient.postObject(uploadRequest, ossRuntime); StringimageURL="http://"+authResponse.bucket+"."+authResponse.endpoint+"/"+authResponse.objectKey+""; returnimageURL; } RuntimeOptions_runtime; com.aliyun.openplatform20191219.Client_authClient; com.aliyun.oss.models.Config_ossConfig; StringossEndpointType=null; staticMap<String, ViapiFileUtilAdvance>_map=newConcurrentHashMap<>(); }
3.测试结果
生成的图片地址=http://viapi-customer-pop.oss-cn-shanghai.aliyuncs.com/ce67_212614432711017986_7857979ccbdf4c3e91aeaeef84effb00
注意事项:
在添加代码块之后,在使用try内包含流会报:“try-with-resource are not supported at language level “5”错误。通过IDEA自带的alt+enter修复功能设置一个版本到7即可。
更多参考:
衣冠の禽兽CSDN文档:IDEA 报错:not supported at language level "5"
ChaseDreamBoy CSDN文档:idea maven 出现:Try-with-resources are not supported at language level '5'