(1) : you must first open related services on alicloud OSS. For details, please refer to this link:
https://help.aliyun.com/document_detail/31883.html?spm=5176.10695662.1996646101.searchclickresult.5ceb3ee82NzMq7&aly_as=WhUj5kPK
Or for video address, please refer to this link: http://cloud.video.taobao.com/play/u/2955313663/p/1/e/6/t/1/2187858851580.mp4
(2) : for alicloud OSS FAQs and introduction, please refer to this link:
https://yq.aliyun.com/articles/716527?spm=a2c4e.11155472.0.0.2fe35cbed5F3GK
(3) : refer to this link for Alibaba cloud OSS error query and problem solving:
https://error-center.aliyun.com/status/product/Oss
You can also ask questions here:
https://selfservice.console.aliyun.com/ticket/createIndex
(4) : introduction to basic functions
Initialize create storage space upload file cross domain access settings set read and write permissions
1. Initialization:
private string accessKeyId = "xxxxxxxxx"; private string accessKeySecret = "xxxxxxxxxx"; private string endpoint = "oss-cn-beijing.aliyuncs.com"; //private static OssClient ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret);
2. Create storage space:
ossClient.CreateBucket("myBucket"); //Create a new Bucket
3. Set read / write permission:
//CannedAccessControlList has three properties: Private, PublicRead, and PublicReadWrite ossClient.SetBucketAcl("myBucket", CannedAccessControlList.PublicRead); //Set as public read
4. Cross domain access settings:
var req = new SetBucketCorsRequest("myBucket"); var rule = new CORSRule(); //Specify the source from which cross domain requests are allowed rule.AddAllowedOrigin("*"); //Specify the allowed cross domain request methods (GET/PUT/DELETE/POST/HEAD) rule.AddAllowedMethod("POST"); //Controls whether the headers specified in the access control request headers header in the OPTIONS prefetch instruction are allowed. rule.AddAllowedHeader("*"); req.AddCORSRule(rule); ossClient.SetBucketCors(req);
(5) : the code example is as follows
1: Upload
During code writing, you need to first understand the following codes:
OSS oSSClient = new OSSClientBuilder().build(ENDPOINTBEIJING,ACCESSKEYID,ACCESSKEYSECRET); ossClient.shutdown();
Understanding: compare the input and output flow to understand that if you want to start the flow and close the flow at last, you need to open and close the flow when trying it out each method in the swagger. If the open flow is shared by all methods (declared as a member variable) after such a method runs, the flow will be closed, and it will not be able to execute the next method (it has to be reopened). Do not turn it on
OSS oSSClient = new OSSClientBuilder().build(ENDPOINTBEIJING,ACCESSKEYID,ACCESSKEYSECRET); declared as a member variable
SendFileController
package com.richfit.richfit.controller; import com.aliyun.oss.model.ObjectMetadata; import com.richfit.richfit.service.DownFileService; import com.richfit.richfit.service.SendFileService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.FileNotFoundException; import java.net.URL; /** * @ClassName SendFileController * @Description: Upload files * @Author BruthLi * @Date 2020/2/4 * @Version V1.0 **/ @Api(value = "Upload or download files") @RestController @RequestMapping(value = "/sys/sendfile") @Slf4j public class SendFileController { @Autowired private SendFileService sendFileService; @Autowired private DownFileService downFileService; //Path to the file on the local or server //private final String filePath="E:\\picture\\15C1D7875F17BE8808191E8A8B2EA1D6.jpg"; @ApiOperation(value = "Obtain OSS picture,Documents, network flow URL For database saving",notes = "Obtain OSS picture,Documents, network flow URL For database saving") @RequestMapping(value = "/getOSSUrl",method = RequestMethod.GET) public URL getOSSUrl(@ApiParam(name = "key",value = "OSS upper OSS picture,Documents, network flow URL Name",required = true) @RequestParam(value = "key",required = true) String key, @ApiParam(name = "bucketName",value = "OSS upper Bucket Name",required = true) @RequestParam(value = "bucketName",required = true)String bucketName) throws FileNotFoundException { return sendFileService.getOSSUrl(key,bucketName); } @ApiOperation(value = "upload OSS Picture or video,Upload a picture or a video",notes = "upload OSS Picture or video,Upload a picture or a video for example beautyleg/beautyleg3.jpg,Will create a beautylegde Folder") @RequestMapping(value = "/sendosspicture",method = RequestMethod.POST) public boolean putObject( @ApiParam(name = "bucketName",value = "OSS upper Bucket Name",required = true) @RequestParam(value = "bucketName",required = true) String bucketName, @ApiParam(name = "key",value = "OSS The name of the picture or video above",required = true) @RequestParam(value = "key",required = true) String key, @ApiParam(name = "filePath",value = "Path to the file on the local or server",required = true) @RequestParam(value = "filePath",required = true) String filePath) throws FileNotFoundException { return sendFileService.putObject(bucketName,key,filePath); } @ApiOperation(value = "delete OSS Picture above,Delete a picture",notes = "delete OSS Picture above,Delete a picture") @RequestMapping(value = "/deleteosspicture",method = RequestMethod.DELETE) public boolean deleteOssObject(@ApiParam(name = "key",value = "OSS The name of the picture above",required = true) @RequestParam(value = "key",required = true) String key, @ApiParam(name = "bucketName",value = "OSS upper Bucket Name",required = true) @RequestParam(value = "bucketName",required = true)String bucketName){ return sendFileService.deleteOssObject(key,bucketName); } /** * .zip .hprof .jpg .txt .mp4 Wait for many formats to upload to OSS * @param bucketName * @param key * @param filePath * @return * @throws FileNotFoundException */ @ApiOperation(value = "upload OSS File",notes = "upload OSS File,Be careful filepath,key Same format for example .txt") @RequestMapping(value = "/sendossfile",method = RequestMethod.POST) public boolean sendOssFile( @ApiParam(name = "bucketName",value = "OSS upper Bucket Name",required = true) @RequestParam(value = "bucketName",required = true) String bucketName, @ApiParam(name = "key",value = "OSS The name of the document on",required = true) @RequestParam(value = "key",required = true) String key, @ApiParam(name = "filePath",value = "Path to the file on the local or server",required = true) @RequestParam(value = "filePath",required = true) String filePath) throws FileNotFoundException { return sendFileService.sendOssFile(bucketName,key,filePath); } @ApiOperation(value = "upload OSS Network flow",notes = "upload OSS Network flow") @RequestMapping(value = "/sendossstream",method = RequestMethod.POST) public boolean sendossstream( @ApiParam(name = "bucketName",value = "OSS upper Bucket Name",required = true) @RequestParam(value = "bucketName",required = true) String bucketName, @ApiParam(name = "key",value = "OSS Name of network flow,It's easy to write, for example lol jk",required = true) @RequestParam(value = "key",required = true) String key, @ApiParam(name = "streamPath",value = "Link address",required = true) @RequestParam(value = "streamPath",required = true) String streamPath) throws FileNotFoundException { return sendFileService.sendossstream(bucketName,key,streamPath); } /** * It can be downloaded to many local formats such as. Zip. Hprof. Jpg. TXT. MP4 * The download function is OK now, but the foreground reports an error: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: * @param objectName * @param bucketName * @param localFileAddressName * @return */ @ApiOperation(value = "download OSS What already exists on,Save to local file,",notes = "download OSS What already exists on,Save to idea Project specific file") @RequestMapping(value = "/downossfile",method = RequestMethod.POST) public ObjectMetadata downOssFile(@ApiParam(name = "objectName",value = "OSS The name of something already exists on, for example tt.jpg",required = true) @RequestParam(value = "objectName",required = true) String objectName, @ApiParam(name = "bucketName",value = "OSS upper Bucket Name",required = true) @RequestParam(value = "bucketName",required = true)String bucketName, @ApiParam(name = "localFileAddressName",value = "Download new production document name,If .zip The end can be downloaded as a compressed package",required = true) @RequestParam(value = "localFileAddressName",required = true)String localFileAddressName){ return downFileService.downOssFile(objectName ,bucketName,localFileAddressName); } }
SendFileServiceImpl
package com.richfit.richfit.service; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.ObjectListing; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectResult; import com.richfit.richfit.OSSClientUtil; import org.springframework.stereotype.Service; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.util.Date; /** * @ClassName SendFileServiceImpl * @Description: Upload files * @Author BruthLi * @Date 2020/2/4 * @Version V1.0 **/ @Service public class SendFileServiceImpl implements SendFileService{ /** * Get OSS pictures, documents, network flow URL * Similar to http://tylgd.oss-cn-beijing.aliyuncs.com/beautyleg1.jpg? Expires = 1580794877 & ossaccesskeyid = ltaizstybwtvdqmn & Signature = yahze% 2bvh4zihn5% 2bbrz1lq0hbtbo% 3D * @return */ @Override public URL getOSSUrl(String key, String bucketName) { Date date = new Date(new Date().getTime()); OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing(); URL url = ossClientBeiJing.generatePresignedUrl(bucketName, key, date); return url; } /** * Upload OSS picture upload a picture or a video (for example,. mp4) * @return */ @Override public boolean putObject(String bucketName,String key,String filePath) { // key refers to the path + filename saved on oss // filePath refers to the uploaded file path //Parameter setting //For this endPoint, please refer to: http://bbs.aliyun.com/read/149100.html?spm=5176.7189909.0.0.YiwiFw //The bucket you are attempting to access must be addressed using the specified endpoint. Please send //System. Out. Println ("error message:" + OE. Geterrorcode()); prompt you how to write endpoint //https://blog.csdn.net/torpidcat/article/details/82867093 endpoint error prompt //String bucketName = "tylgd"; //File name saved on oss //String key="beautyleg1.jpg"; //Path to the file on the local or server //String filePath="E:\picture\15C1D7875F17BE8808191E8A8B2EA1D6.jpg"; / / path to the local or server file boolean flag=false; OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing(); try{ // Get the input stream of the specified file File file = new File(filePath); InputStream content = new FileInputStream(file); // Create the Metadata of the uploaded Object ObjectMetadata meta = new ObjectMetadata(); // ContentLength must be set meta.setContentLength(file.length()); // Upload Object PutObjectResult result = ossClientBeiJing.putObject(bucketName, key, content, meta); if (file.isFile() && file.exists()) { flag = true; } }catch(OSSException oe){ System.out.println("Error Message: " + oe.getErrorMessage()); System.out.println("Error Code: " + oe.getErrorCode()); System.out.println("Request ID: " + oe.getRequestId()); System.out.println("Host ID: " + oe.getHostId()); flag=false; }finally { ossClientBeiJing.shutdown(); return flag; } } /** * Delete a picture on OSS delete a picture * @param key The name of the image on OSS * @return */ @Override public boolean deleteOssObject(String key,String bucketName) { OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing(); boolean b = ossClientBeiJing.doesObjectExist(bucketName, key); //If it exists, it returns true b is true if (b){ ObjectListing objectListing = ossClientBeiJing.listObjects(bucketName); ossClientBeiJing.deleteObject(bucketName,key); ossClientBeiJing.shutdown(); return true; } return false; } /** * Upload OSS documents * @param filePath bucketName key * @return */ @Override public boolean sendOssFile(String bucketName,String key,String filePath) { boolean flag=false; OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing(); try{ // Get the input stream of the specified file File file = new File(filePath); InputStream content = new FileInputStream(file); // Create the Metadata of the uploaded Object //ObjectMetadata meta = new ObjectMetadata(); // ContentLength must be set //meta.setContentLength(file.length()); // Upload Object PutObjectResult result = ossClientBeiJing.putObject(bucketName, key, content); if (file.isFile() && file.exists()) { flag = true; } }catch(OSSException oe){ System.out.println("Error Message: " + oe.getErrorMessage()); System.out.println("Error Code: " + oe.getErrorCode()); System.out.println("Request ID: " + oe.getRequestId()); System.out.println("Host ID: " + oe.getHostId()); flag=false; }finally { ossClientBeiJing.shutdown(); return flag; } } /** * Upload OSS network stream * @param bucketName * @param key * @param streamPath * @return */ @Override public boolean sendossstream(String bucketName, String key, String streamPath) { boolean flag=true; OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing(); try{ // Get the input stream of the specified file InputStream content = new URL(streamPath).openStream(); PutObjectResult result = ossClientBeiJing.putObject(bucketName, key, content); }catch(OSSException oe){ System.out.println("Error Message: " + oe.getErrorMessage()); System.out.println("Error Code: " + oe.getErrorCode()); System.out.println("Request ID: " + oe.getRequestId()); System.out.println("Host ID: " + oe.getHostId()); flag=false; }finally { ossClientBeiJing.shutdown(); return flag; } } }
OSSClientUtil
In fact, Alibaba cloud OSS has its own OSS utils, but it has another one for its own convenience
package com.richfit.richfit; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; /** * @ClassName OSSClient * @Description: In fact, Alibaba cloud OSS has its own OSS utils, but it has another one for its own convenience * @Author BruthLi * @Date 2020/2/4 * @Version V1.0 **/ public class OSSClientUtil { //http://oss-cn-hangzhou.aliyuncs.com public static final String ENDPOINTBEIJING = "http://oss-cn-beijing.aliyuncs.com "; / / interface to Beijing public static final String ACCESSKEYID = "**********"; public static final String ACCESSKEYSECRET = "*********"; /** * OSSClient in Beijing * @return */ public static OSS getOssClientBeiJing(){ OSS oSSClient = new OSSClientBuilder().build(ENDPOINTBEIJING,ACCESSKEYID,ACCESSKEYSECRET); return oSSClient; } /** * OSSClient in Hangzhou * @return */ /* public OSSClient getOssClientHangZhou(){ OSSClient oSSClient = new OSSClient(endpointbeijing,accessKeyId,accessKeySecret); return oSSClient; }*/ }
2: Download
DownFileController
/** * It can be downloaded to many local formats such as. Zip. Hprof. Jpg. TXT. MP4 * The download function is OK now, but the foreground reports an error: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: * @param objectName * @param bucketName * @param localFileAddressName * @return */ @ApiOperation(value = "download OSS What already exists on,Save to local file,",notes = "download OSS What already exists on,Save to idea Project specific file") @RequestMapping(value = "/downossfile",method = RequestMethod.POST) public ObjectMetadata downOssFile(@ApiParam(name = "objectName",value = "OSS The name of something already exists on, for example tt.jpg",required = true) @RequestParam(value = "objectName",required = true) String objectName, @ApiParam(name = "bucketName",value = "OSS upper Bucket Name",required = true) @RequestParam(value = "bucketName",required = true)String bucketName, @ApiParam(name = "localFileAddressName",value = "Download new production document name,If .zip The end can be downloaded as a compressed package",required = true) @RequestParam(value = "localFileAddressName",required = true)String localFileAddressName){ return downFileService.downOssFile(objectName ,bucketName,localFileAddressName); }
DownFileService
ObjectMetadata downOssFile(String objectName, String bucketName, String localFileAddressName);
DownFileServiceImpl
package com.richfit.richfit.service; import com.aliyun.oss.OSS; import com.aliyun.oss.model.CannedAccessControlList; import com.aliyun.oss.model.GetObjectRequest; import com.aliyun.oss.model.ObjectMetadata; import com.richfit.richfit.OSSClientUtil; import org.springframework.stereotype.Service; import java.io.File; /** * @ClassName downFileServiceImpl * @Description: Download what already exists on OSS * @Author BruthLi * @Date 2020/2/4 * @Version V1.0 **/ @Service public class DownFileServiceImpl implements DownFileService { /** * Download the existing things on OSS and save them to the specified file of idea project * @param objectName * @param bucketName * @return */ @Override public ObjectMetadata downOssFile(String objectName, String bucketName,String localFileAddressName) { //String localFileAddressName="src/main/resources/files"; OSS ossClient = null; ObjectMetadata object = null; try { //Create an OSSClient instance to operate oss space ossClient = OSSClientUtil.getOssClientBeiJing(); ossClient.setBucketAcl("tylgd", CannedAccessControlList.PublicReadWrite); //Specify file save path //String filePath = localFileAddressName+"/"+System.currentTimeMillis()+".jpg"; //Determine whether the file directory exists. If not, create the end of. Zip. Hprof File file = new File(localFileAddressName,System.currentTimeMillis()+".mp4"); boolean newFile = file.createNewFile(); if (newFile){ file.setWritable(true); object = ossClient.getObject(new GetObjectRequest(bucketName, objectName), file); return object; } } catch (Exception e) { e.printStackTrace(); }finally { ossClient.shutdown(); } //Determine whether to add suffix to the saved file name /*if (objectName.contains(".")){ //Specify file save name filePath = filePath+"/"+objectName.substring(objectName.lastIndexOf("/")+1); }*/ //Get the OSS file and save it to the local specified path. The file path must exist. If the save directory does not exist, an error will be reported. If the save file name already exists, the local file will be overwritten return object; } }
OSSClientUtil
package com.richfit.richfit; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; /** * @ClassName OSSClient * @Description: * @Author BruthLi * @Date 2020/2/4 * @Version V1.0 **/ public class OSSClientUtil { //http://oss-cn-hangzhou.aliyuncs.com public static final String ENDPOINTBEIJING = "http://oss-cn-beijing.aliyuncs.com "; / / interface to Beijing public static final String ACCESSKEYID = "********"; public static final String ACCESSKEYSECRET = "************"; /** * OSSClient in Beijing * @return */ public static OSS getOssClientBeiJing(){ OSS oSSClient = new OSSClientBuilder().build(ENDPOINTBEIJING,ACCESSKEYID,ACCESSKEYSECRET); return oSSClient; } /** * OSSClient in Hangzhou * @return */ /* public OSSClient getOssClientHangZhou(){ OSSClient oSSClient = new OSSClient(endpointbeijing,accessKeyId,accessKeySecret); return oSSClient; }*/ }
3: Texting
SendSmsController
package com.richfit.richfit.controller; /** * @ClassName SendSms * @Description: Alibaba cloud sends SMS SendSms and Alibaba cloud sends verification code SendSms * @Author BruthLi * @Date 2020/2/3 * @Version V1.0 **/ import com.richfit.richfit.service.SendSmsService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Map; /* pom.xml <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.0.3</version> </dependency> */ @Api(value = "Send SMS or verification code") @RestController @RequestMapping(value = "/sys/sendmessagecode") @Slf4j public class SendSmsController { @Autowired private SendSmsService sendSmsService; final String phoneNumber = "**************"; @ApiOperation(value = "Check whether the verification code is correct",notes = "Check whether the verification code is correct") @RequestMapping(value = "/sendcodeyesorno",method = RequestMethod.GET) public Map<String,String> sendCodeYesOrNo(String inputcode){ Map<String, String> mapReturn = sendSmsMessage(phoneNumber); String code = mapReturn.get("code"); if (code.equalsIgnoreCase(inputcode)){ return mapReturn; } mapReturn.put("code", "Verification Code:["+inputcode+"]Incorrect input, please input again!"); return mapReturn; } /** * Send SMS or verification code * @param phoneNumber Phone number * @return HttpServletRequest */ @ApiOperation(value = "Send SMS or verification code",notes = "Send SMS or verification code") @RequestMapping(value = "/sendcode",method = RequestMethod.POST) public Map<String, String> sendSmsMessage(String phoneNumber) { return sendSmsService.sendSmsMessage(phoneNumber); } }
SendSmsServiceImpl
package com.richfit.richfit.service; import com.aliyuncs.CommonRequest; import com.aliyuncs.CommonResponse; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * @ClassName SendSmsServiceImpl * @Description: * @Author BruthLi * @Date 2020/2/4 * @Version V1.0 **/ @Service public class SendSmsServiceImpl implements SendSmsService { /** * Send SMS or verification code * @param phoneNumber * @return */ @Override public Map<String, String> sendSmsMessage(String phoneNumber) { String jsonCode = "{code:" + (int) ((Math.random() * 9 + 1) * 100000) + "}"; CommonResponse response = null; Map<String, String> mapCode = new HashMap<>(); DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "*************", "*****************"); IAcsClient client = new DefaultAcsClient(profile); CommonRequest request = new CommonRequest(); request.setMethod(MethodType.POST); request.setDomain("dysmsapi.aliyuncs.com"); request.setVersion("2017-05-25"); request.setAction("SendSms"); request.putQueryParameter("RegionId", "cn-hangzhou"); //Phone numbers and TemplateParam can be changed. Other values are fixed after Alibaba cloud application request.putQueryParameter("PhoneNumbers", phoneNumber); request.putQueryParameter("SignName", "BruthLi"); request.putQueryParameter("TemplateCode", "SMS_183150435"); //In this definition, the content name of the text message you send is the same: the following values can be changed //request.putQueryParameter("TemplateParam","{'name': 'Mom, have you eaten'}"); //Send 6-digit verification code request.putQueryParameter("TemplateParam", jsonCode); try { response = client.getCommonResponse(request); if (response.getHttpStatus() == 200) { mapCode.put("code", jsonCode); } } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } return mapCode; } }
(6) : error reporting
(1) : when downloading, report a: access denied drive letter access denied
java.io.FileNotFoundException: E:\oilrichfit\richfit\src\main\resources\files\1580826234328.jpg (Access denied.)
This error is caused by no access to the drive letter or OSS bucket
Add the following code to the appropriate location of the solution:
//CannedAccessControlList has three properties: Private and PublicRead ossClient.setBucketAcl("tylgd", CannedAccessControlList.PublicReadWrite); File file = new File(localFileAddressName,System.currentTimeMillis()+".mp4"); file.setWritable(true);
(2) : when downloading, the function can be realized, but the foreground still reports one error (which has not been solved yet): org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: