阿里存储OSS上传和下载

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.itheima.controller.result.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/*文件上传下载*/
@RequestMapping("/common")
@RestController
@Slf4j
public class CommonController {
    @Value("${ji.path}")//yml自己配置文件路径
    //ji:
    //path: D:
    private String filepath;

    /*图片文件下载*/
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws FileNotFoundException {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + substring;
        log.info("存储照片名称为" + filename);
        /*原存储方式*/
        File file1 = new File(filepath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(filepath + filename));
            /*oss*/
            /*将图片上传到oss存储仓库*/
            // Endpoint以杭州为例,其它Region请按实际情况填写。
            String endpoint = "http://oss-cn-nanjing.aliyuncs.com";
            // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = "";
            String accessKeySecret = "";
            String bucketName = "";
            // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
            String localFile = filepath + filename;
            String fileKeyName = filename;
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            InputStream inputStream = new FileInputStream(localFile);
            ossClient.putObject(bucketName, "oss文件目录位置/" + fileKeyName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            return R.success(filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("下载失败");


    }

    /*图片上传*/
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
       /* try {
            FileInputStream fileInputStream = new FileInputStream(new File(filepath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            IOUtils.copy(fileInputStream, outputStream);
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "http://oss-cn-nanjing.aliyuncs.com";
// 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
        String accessKeyId = "";
        String accessKeySecret = "";
// 从STS服务获取的安全令牌(SecurityToken)。
        /* String securityToken = "yourSecurityToken";*/
// 填写Bucket名称,例如examplebucket。
        String bucketName = "";
// 填写Object完整路径,例如exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "download/" + name;

// 从STS服务获取临时访问凭证后,您可以通过临时访问密钥和安全令牌生成OSSClient。
// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 通过STS临时授权将Object下载本地文件。如果指定的本地文件存在则覆盖,不存在则新建。
// 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
        OSSObject ossObject = ossClient.getObject(bucketName, objectName);
        response.setContentType("image/jpeg");//自定义响应文件类型
        ServletOutputStream outputStream = response.getOutputStream();
        InputStream fileInputStream = ossObject.getObjectContent();
       /* byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }*/
        IOUtils.copy(fileInputStream, outputStream);
        outputStream.close();
        fileInputStream.close();
// 关闭OSSClient。
        ossClient.shutdown();
    }
}

依赖
 <!--阿里osssdk-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>
<!--ossJDK9以上相关依赖-->
        <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>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.3</version>
        </dependency>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

20岁30年经验的码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值