OSS图片上传

添加SDK依赖

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

工具类

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author Jude
 */
@Component
public class OssTemplate {
    private final static String ACCESS_KEY_ID = "你的KEY_ID";

    private final static String ACCESS_KEY_SECRET = "你的KEY_SECRET";
                                            //你的水桶名字
    private final static String BUCKET_NAME = "qzp";

                        //url不知道在哪里的直接百度
    private final static String URL = "https://qzp.oss-cn-hangzhou.aliyuncs.com/";

    private final static String ENDPOINT = "oss-cn-hangzhou.aliyuncs.com";

    /**
     * 文件上传工具类
     *
     * @param suffixName 图片的格式名
     * @param is         字节输出流
     * @return 文件上传地址
     */
    public String upload(String suffixName, InputStream is) {
//        String filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
//                + "/" + UUID.randomUUID() + "." + suffixName;
        String filename = "reggie-img/菜品图片/" + UUID.randomUUID() + "." + suffixName;

//        System.out.println(filename);

        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        ossClient.putObject(BUCKET_NAME, filename, is);

        ossClient.shutdown();

        String ossUrl = URL + "/" + filename;

        System.out.println(ossUrl);

        return ossUrl;
    }

    /**
     * 文件下载
     * @param fileName 云端文件名
     */
    public static void download(String fileName){
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = ACCESS_KEY_ID;
        String accessKeySecret = ACCESS_KEY_SECRET;
        // 填写Bucket名称,例如examplebucket。
        String bucketName = BUCKET_NAME;
        // 填写不包含Bucket名称在内的Object完整路径,例如testfolder/exampleobject.txt。
        String objectName = "菜品图片/"+fileName;
        //这里的路径写你要保存的文件夹的路径
        String pathName = "D:\\code\\reggie-code\\picture"+fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
            // 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            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());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static void main(String[] args) {
        download("02e244ba-be98-40b5-b0b9-929e6efae56a.jpg");
    }
}

controller层

import com.itheima.common.R;
import com.itheima.utils.OssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
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 java.io.IOException;
import java.io.InputStream;

/**
 * @author ning
 * @date 2022/6/14 15:31
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private OssTemplate ossTemplate;

    /**
     * 图片上传
     *
     * @return
     */
    @PostMapping("/upload")
//R是返回的结果集,使用的时候改成你们公司自己的
    public R upload(MultipartFile file) {

        try {
            InputStream inputStream = file.getInputStream();
            //上传图片的格式
            String name = "jpg";
            String upload = ossTemplate.upload(name, inputStream);
            return R.success(upload);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

常见的问题

数据库存放图片的字段约束太短,会出现可以上传,阿里云控制台可以看到,但是自己项目里看不到的现象。因为数据库里保存的是网址,有时候个别图片的网址会很长,   我直接用varchar(500)就没问题了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值