如何使用阿里云oss存储项目的图片 Posted on 2019-09-05 | In oss | Visitors | Words count in article: 319 | Reading time ≈ 1 引入阿里云oss的依赖123456<!-- 阿里云oss组件 --><dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.5.0</version></dependency> 简单封装oss的连接12345678910111213/** * 获取连接oss的链接 * @return 返回一个oss的链接 */ fun getOssClient() : OSS{ val endpoint = "<yourEndpoint>" // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。 val accessKeyId = "<yourAccessKeyId>" val accessKeySecret = "<yourAccessKeySecret>" // 创建OSSClient实例。 val ossClient = OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret) return ossClient } 上传文件的实现12345678910111213141516171819202122232425262728/** * 将文件上传到阿里云oss * @param file 需要上传的文件 * @return 文件的访问路径 (返回-1说明上传失败) */ fun uploadFile(file : MultipartFile) : String{ val dt = Date() val sdf = SimpleDateFormat("yyyyMMdd") var fileName = sdf.format(dt) + "/" + UUID.randomUUID() + "." + file.contentType.split("/")[1] // 创建OSSClient实例。 val ossClient = getOssClient() try { // OSS操作,例如上传文件 ossClient.putObject("<yourBucketName>", fileName, file.inputStream) return fileName } catch (oe : OSSException) { println("Error Message: " + oe.errorMessage) println("Error Code: " + oe.errorCode) println("Request ID: " + oe.requestId) println("Host ID: " + oe.hostId) return "-1" } catch (ce : ClientException) { println("Error Message: " + ce.errMsg) return "-1" } finally { ossClient?.shutdown() } } 实现参考自阿里云官方文档 -------------本文结束您的阅读与肯定是我持续装*的最大动力-------------