欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Play搭建腾讯云COS

程序员文章站 2024-03-14 10:05:28
...

腾讯云开通储存桶

Play搭建腾讯云COS
这边获得四个重要参数
Play搭建腾讯云COS

maven配置

		<dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.5.2</version>
        </dependency>

前端代码

<div id="div1">
    <div class="alertLeft">
        <div class="displayFlex">
            <div class="FlexOne">
                <a >
                    上传照片<input size="100" type="file" name="file" id="file" @change="bannerChange" >
                </a>
            </div>
            <div class="FlexOne">
                <div class="setting_index_banner">
                    <img style="width: 50px" :src="bannerFile">
                </div>
            </div>
            <div class="FlexOne">
                <div class="setting_index_banner">
                    <img style="width: 100px;" :src="imgUrl">
                </div>
            </div>
        </div>
    </div>
    <button class="saveBtn mr20" @click="bannerSave()">确定</button>
</div>
</body>
</html>
<script>
    new Vue({
        el:"#div1",
        data:{
            imgUploadInfo: {
                logo_url: null,
                banner_url: null,
            },
            bannerFile: '',
            imgUrl:'',
        },
        methods:{
            //上传
            bannerChange: function (event) {
                var self = this;
                var file = event.target.files[0];
                self.imgUploadInfo.banner_url = file;
                // 图片预览
                var reader = new FileReader();
                reader.onload = (function (theFile) {
                    return function (e) {
                        self.bannerFile = e.target.result;
                    }
                })(file);
                reader.readAsDataURL(file);
            },
            // //修改banner确定
            bannerSave: function () {
                var self = this;
                var form = new FormData();
                form.append("file", self.imgUploadInfo.banner_url);
                self.$http.post("/good/up", form).then(function (res) {
                    var _data = res.data
                    if (_data.code == 1000) {
                        self.imgUrl = "https://bravery-1258739678.cos.ap-guangzhou.myqcloud.com/"+_data.data;
                        // window.location.reload();
                    }
                }, function (err) {
                    console.log(err)
                })
            },
        }
    })

</script>

后端代码

我用的是play框架 用其他框架只要把文件/图片传过来就可以了

	private static final String ACCESSKEY = "XXXXXXXXXXXXXXXXXX";//可以从腾讯云查到id
    private static final String SECRETKEY = "XXXXXXXXXXXXXXXXXXXXXX";//查到密码
    private static final String BUCKETNAME = "bravery-1258739678";//改成你们名字
    private static final String APPID = "1258739678";//改成你们appid
    private static final String REGIONID = "ap-guangzhou";//服务器地址
public static COSClient getCosClient() {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(ACCESSKEY, SECRETKEY);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
        ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
        //String bucketName = BUCKETNAME;
        return cosClient;
    }
    public static String uploadFile(File localFile) throws DBException {
//        File localFile = new File("d:\\bg.jpg");
        String fileName = localFile.getName();
        int suffix = fileName.lastIndexOf(".");
        String last_str = fileName.substring(suffix + 1);
        String time_str = String.valueOf(System.currentTimeMillis());
        String imgUrl=time_str+"."+last_str;

        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, imgUrl, localFile);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia),一般为标准的
        putObjectRequest.setStorageClass(StorageClass.Standard);

        COSClient cc = getCosClient();
        try {
            PutObjectResult putObjectResult = cc.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            String etag = putObjectResult.getETag();
            System.out.println(etag);
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        ImgDao.story(imgUrl);
        cc.shutdown();
        return imgUrl;
    }

    public static void cosTest(File file) throws DBException {
        COSClient cosClient = getCosClient();
        System.out.println("111");
        String imgUrl = uploadFile(file);
        renderSuccDataResult(imgUrl);
    }

效果

数据库
Play搭建腾讯云COS
腾讯cos
Play搭建腾讯云COS

总结

相当于把图片改好名字放到公网
https://bravery-1258739678.cos.ap-guangzhou.myqcloud.com/1557222244420.jpg
然后数据库存图片名字,可以用uuid,我用的是时间戳,总之就是防止重名
返回前端时候获取数据库url返回到前端,前端Play搭建腾讯云COS
Play搭建腾讯云COS