SpringBoot整合七牛雲實現文件以及圖片上傳

關於七牛雲的註冊以及申請存儲空間這裏就不詳細介紹了,網上的教程很多而且註冊以及申請存儲空間也是比較簡單的。直接進入正題,說一下整合的事情。

配置文件application.yml

qiniu:
    accessKey: xxxx-xxxx-xxxx
    secretKey: xxxx_xxxx-xxxx
    bucket: rongdi
    path: http://up-z1.qiniup.com  # 每個地區的地址都不一樣

上面參數對應七牛雲中的配置如下圖
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

創建上傳文件以及圖片的配置類

@Data
@Component
@ConfigurationProperties(prefix = "qiniu")
public class QiNiuYunConfig {

    @Value("${accessKey}")
    private String accessKey;
    @Value("${secretKey}")
    private String secretKey;
    @Value("${bucket}")
    private String bucket;
    @Value("${path}")
    private String path;


    public String uploadImgToQiNiu(FileInputStream file, String filename) {
        // 構造一個帶指定Zone對象的配置類,注意後面的zone各個地區不一樣的
        Configuration cfg = new Configuration(Zone.zone1());
        // 其他參數參考類註釋
        UploadManager uploadManager = new UploadManager(cfg);
        // 生成密鑰
        Auth auth = Auth.create(accessKey, secretKey);
        try {
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(file, filename, upToken, null, null);
                // 解析上傳成功的結果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                // 這個returnPath是獲得到的外鏈地址,通過這個地址可以直接打開圖片
                String returnPath = getPath() + "/" + putRet.key;
                return returnPath;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

Controller層

@Controller
public class QiNiuYunController {

    @Autowired
    private QiNiuYunConfig qiNiuYunConfig;

    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }

    @PostMapping("/qiniu")
    public String qiNiuYunUpload(@RequestParam("file")MultipartFile file,
                                 Model model) throws IOException {
        String filename = file.getOriginalFilename();
        FileInputStream inputStream = (FileInputStream) file.getInputStream();
        //爲文件重命名:uuid+filename
        filename = UUID.randomUUID()+ filename;
        String link = qiNiuYunConfig.uploadImgToQiNiu(inputStream, filename);
        model.addAttribute("link", link);
        return "upload";
    }
}

HTML代碼

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上傳文件</title>
</head>
<body>
<form action="/qiniu" method="post" enctype="multipart/form-data">
    <label>上傳圖片</label>
    <input type="file" name="file"/>
    <input type="submit" value="上傳"/>
    <p>回顯圖片:</p>
    <img th:src="${link}"/>
</form>
</body>
</html>

效果如下

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章