阿里云对象存储OSS图片上传并回显

阿里云对象存储OSS图片上传并回显

Java代码实现

引入依赖

       <!--  引入阿里云OSS依赖-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.2</version>
        </dependency>

controller层

只是练习所以实现代码直接写在了controller里

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Controller
public class OssController {
    
    public static String ENDPOINT = "<yourENDPOINT>";
    public static String ACCESSKEYID = "<yourACCESSKEYID>";
    public static String ACCESSKEYSECRET = "<yourACCESSKEYSECRET>";
    public static String BUCKETNAME = "<yourOBUCKETNAME>";
    public static String PATH = "<yourOSS文件夹>/";
    
    @RequestMapping(value = "/upload")
    public String myphotoupload(MultipartFile file , Model model) {

        try {
            // 创建OSS实例
            OSSClient ossClient = new OSSClient(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
            // 获取上传的文件的输入流
            InputStream inputStream = file.getInputStream();
            // 获取文件名称
            String fileName = file.getOriginalFilename();

            // 在文件名称里面添加随机唯一值,使用UUID生成  把uuid生成里的-去掉
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
			// 拼接fileName  PATH是oss文件夹
            fileName = PATH + fileName;
            
            /**
             * 调用oss方法实现上传
             * 第一个参数 Bucket名称
             * 第二个参数 上传oss文件路径和名称 aa/bb/1.jpg
             * 第三个参数 上传文件的输入流
             */
            
            //ossClient.putObject(BUCKETNAME, fileName, inputStream);   用这种方式putObject上传,拼接的url是下载!!!
            //ossClient.shutdown();

            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, fileName, inputStream);
            ossClient.putObject(putObjectRequest);
            // 关闭ossClient
            ossClient.shutdown();
            // 把上传到oss的路径返回
            // 需要将路径手动拼接出来,https://xxxxxx.oss-cn-shanghai.aliyuncs.com/edu/avatar/girl.jpg
            String url = "https://"+ BUCKETNAME + "." + ENDPOINT + "/" + fileName;
            System.out.println(url);
            model.addAttribute("url", url);
            return "demo";//demo.html
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("url","");
            return "demo";
        }

    }

}

页面

上传页面

<form action="/photoupload" method="post" enctype="multipart/form-data">
    <input type="file" name="file"  required/>
    <input type="submit" value="提交">
</form>
回显
<img th:src="${url}" th:width="100px" th:high="100px"/>
上一篇:关于redis源码的内存分配,jemalloc,tcmalloc,libc


下一篇:对象存储OSS