栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

阿里云对象存储OSS文件上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

阿里云对象存储OSS文件上传

阿里云oss地址:

对象存储OSS_云存储服务_企业数据管理_存储-阿里云阿里云对象存储OSS是一款海量、安全、低成本、高可靠的云存储服务,提供12个9的数据持久性,99.995%的数据可用性和多种存储类型,适用于数据湖存储,数据迁移,企业数据管理,数据处理等多种场景,可对接多种计算分析平台,直接进行数据处理与分析,打破数据孤岛,优化存储成本,提升业务价值。https://www.aliyun.com/product/oss?spm=5176.19720258.J_3207526240.31.e9392c4aXvq4LI

学习的oss的,阿里云有提供免费的。

 

 

 

 地域可以选择距离自己最近的

 点击右上角的图片

 

保存自己的 AccessKey ID,AccessKey Secret

 导入依赖


    com.aliyun.oss
    aliyun-sdk-oss
    3.10.2


     joda-time
     joda-time
     2.10.6

 配置文件,我使用的是yml

# 阿里云oss配置
aliyun:
  oss:
    endpoint: oss-cn-beijing.aliyuncs.com # 对应公网endpoint地址
    accessKeyId: #改成自己的AccessKey ID
    accessKeySecret: #改成自己的AccessKey Secret
    bucketname: #改成自己的Bucket 列表
    urlPrefix: active #保存文件夹路径

package com.tm.conf;

import java.util.HashMap;
import java.util.Map;



public class AjaxResult extends HashMap {
    private static final long serialVersionUID = 1L;

    
    public AjaxResult() {
    }

    
    public static AjaxResult error() {
        return error(1, "操作失败");
    }

    
    public static AjaxResult error(String msg) {
        return error(500, msg);
    }

    
    public static AjaxResult error(int code, String msg) {
        AjaxResult json = new AjaxResult();
        json.put("code", code);
        json.put("msg", msg);
        return json;
    }

    
    public static AjaxResult error(int code, String msg, Object data) {
        AjaxResult json = new AjaxResult();
        json.put("code", code);
        json.put("msg", msg);
        json.put("data", data);
        return json;
    }

    
    public static AjaxResult success(String msg) {
        AjaxResult json = new AjaxResult();
        json.put("msg", msg);
        json.put("code", 0);
        return json;
    }

    
    public static AjaxResult success(Object data) {
        AjaxResult json = new AjaxResult();
        json.put("msg", "");
        json.put("code", 0);
        json.put("data", data);

        return json;
    }

    
    public static AjaxResult success(Map map) {
        AjaxResult json = new AjaxResult();
        json.put("msg", "");
        json.put("code", 0);
        json.putAll(map);

        return json;
    }

    
    public static AjaxResult success(Object[] data) {
        AjaxResult json = new AjaxResult();
        json.put("msg", "");
        json.put("code", 0);
        json.put("data", data);

        return json;
    }

    
    public static AjaxResult success() {
        return AjaxResult.success("操作成功");
    }

    
    @Override
    public AjaxResult put(String key, Object value) {
        super.put(key, value);
        return this;
    }

}
package com.tm.conf;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = "classpath:application.yml") //指定配置文件的位置
public class AliConfig implements InitializingBean {
    
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    
    @Value("${aliyun.oss.bucketname}")
    private String bucketName;

    
    @Value("${aliyun.oss.urlPrefix}")
    private String folder;

    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;
    public static String FOLDER;

    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endpoint;
        ACCESS_KEY_ID = accessKeyId;
        ACCESS_KEY_SECRET = accessKeySecret;
        BUCKET_NAME = bucketName;
        FOLDER = folder;
    }
}

package com.tm.conf;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import org.springframework.beans.factory.annotation.Value;

import java.net.URL;
import java.util.Date;


public class OssUtil {

    
    @Value("${aliyun.oss.endpoint}")
    private String aliyunDomain;

    
    @Value("${aliyun.oss.accessKeyId}")
    private String aliyunAccessKeyId;

    
    @Value("${aliyun.oss.accessKeySecret}")
    private String aliyunAccessKeySecret;

    
    @Value("${aliyun.oss.bucketname}")
    private String aliyunBucketName;


    
    public String getUrl(String key) {
        OSSClient ossClient = new OSSClient(aliyunDomain, aliyunAccessKeyId, aliyunAccessKeySecret);
        // 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        GeneratePresignedUrlRequest generatePresignedUrlRequest;
        generatePresignedUrlRequest = new GeneratePresignedUrlRequest(aliyunBucketName, key);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }
}
package com.tm.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.tm.conf.AliConfig;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;
import java.util.Arrays;
import java.util.Base64;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {
    @PostMapping
    public String uploadFile(@RequestBody MultipartFile file) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = AliConfig.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = AliConfig.ACCESS_KEY_ID;
        String accessKeySecret = AliConfig.ACCESS_KEY_SECRET;
        String backetName = AliConfig.BUCKET_NAME;
        String fileName=AliConfig.FOLDER;
        String code = null;
        String uploadUrl = null;
        try {
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            // 在文件名称中添加随机的唯一的值,防止名称一样时文件的覆盖
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // 文件类型
            String fileType = filename.substring(filename.lastIndexOf("."));
            filename = uuid + fileType;

            // 把文件安装日期进行分类,会自动创建文件夹
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = fileName+"/"+datePath + "/" + filename;
            ossClient.putObject(backetName, filename, inputStream);
            // 上传文件之后的路径,自己拼接
            uploadUrl = "https://" + backetName + "." + endpoint + "/" + filename;
            //转BYTE
            OSSObject image = ossClient.getObject(backetName, filename);
            InputStream content = image.getObjectContent();
            byte[] bytes = null;
            if (content != null) {
                try {
                    // 设置一个足够大的buffer用于存储图片的比特数据
                    int length = 1920 * 1260 * 3;
                    byte[] buf = new byte[length];
                    int size = 0;
                    int temp;
                    while ((temp = content.read()) != -1) {
                        buf[size] = (byte) temp;
                        size++;
                    }
                    content.close();
                    // 对缓冲区进行裁剪后,将图片以字节数组的形式返回
                    bytes = Arrays.copyOf(buf, size);
                } catch (IOException e) {
                    System.out.println("exception");
                    return null;
                }
            }
            // 关闭OSSClient。
            ossClient.shutdown();
            // 将数组转为字符串
            String s = new String(Base64.getEncoder().encode(bytes));
            code = "data:image/png;base64," + s;
            // 关闭OSSClient
            ossClient.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return code;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/985059.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号