200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 阿里云oss对象存储上传照片并返回照片路径

阿里云oss对象存储上传照片并返回照片路径

时间:2021-09-09 18:09:25

相关推荐

阿里云oss对象存储上传照片并返回照片路径

安装javaJDk

依赖 jdk1.8(只用一个依赖即可)

<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version></dependency><dependency>

使用的是Java 9及以上的版本,则需要添加jaxb相关依赖。

<dependency><groupId>javax.xml.bind</groupId><artifactId>jaxb-api</artifactId><version>2.3.1</version></dependency><dependency><groupId>javax.activation</groupId><artifactId>activation</artifactId><version>1.1.1</version></dependency><!-- no more than 2.3.3--><dependency><groupId>org.glassfish.jaxb</groupId><artifactId>jaxb-runtime</artifactId><version>2.3.3</version></dependency>

程序:

public String uploadFileToOss(MultipartFile multipartFile,String fileCatalog) {//地域节点String endpoint = ".........";// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。//AccessKey管理String accessKeyId = "............";String accessKeySecret = ".........";//bucket名称String bucketName = ".........-oss";// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {//获取文件流InputStream inputStream=multipartFile.getInputStream();//构建日期文件SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd");String datePath=dateFormat.format(new Date());//获取到文件名String originName= multipartFile.getOriginalFilename();//文件名String fileName = UUID.randomUUID().toString();//后缀String suffix=originName.substring(originName.lastIndexOf("."));//新文件名String newName=fileName+suffix;//完整路径String fileUrl="............"+fileCatalog+datePath+"/"+newName;//文件上传到阿里云服务器ossClient.putObject(bucketName,fileUrl,inputStream);//返回路径String filePath="https://"+bucketName+"."+endpoint+"/"+fileUrl;System.out.println(filePath);return filePath;} catch (Exception e) {e.printStackTrace();return "fail";} finally {//关闭ossClientif (ossClient != null) {ossClient.shutdown();}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。