vueフロントエンドからCOSにファイルをアップロードします

1:main.js内

//COS相关的
Vue.prototype.loadi = 'https://images-1254950508.cos.ap-guangzhou.myqcloud.com/a/1588390454918/loading.gif';
console.log(process.env.VUE_APP_serverUrl);
Vue.prototype.$baseUrl = process.env.VUE_APP_serverUrl;
Vue.prototype.fileCos = function (_obj,callback){
    let options = {
        url: '/fileUpload/cos/credential',
        method: 'GET',
    }

    request(options).then(res => { //获取cos令牌
        if(res.code == 0) {
            var cosArg = res.data
            var cos = new COS({
                getAuthorization: function (options, callback) {
                    callback({
                        TmpSecretId: res.data.credentials && res.data.credentials.tmpSecretId,
                        TmpSecretKey: res.data.credentials && res.data.credentials.tmpSecretKey,
                        XCosSecurityToken: res.data.credentials && res.data.credentials.sessionToken,
                        ExpiredTime: res.data.expiredTime
                    });
                }
            })
            var cosKey = `${cosArg.keyPrefix}/${new Date().getTime()}/${_obj.name}`
            cos.putObject({
                Bucket: cosArg.bucket,
                Region: cosArg.region,
                Key: cosKey,
                Body: _obj,
            }, (err, res) => {
                if (!err) {
                    if(res.Location.indexOf('https://') == -1){
                        res.Location = 'https://' + res.Location;
                    }
                    // console.log('图片已经传到cos服务器')
                    // console.log(res)
                    var _data = {
                        'url' : res.Location, // 文件路径
                        'name' : _obj.name, // 文件名
                        'type' : _obj.type, // 文件类型 如:image/jpeg
                        'size' : parseInt(_obj.size/1024), // 文件大小
                    }
                    callback(_data);
                }
            })
        }else {
            this.$Message.error({
                content: '上报错误:'+res.msg,
                duration: 0,
                closable: true,
            })
        }
    }).catch(error => {
        console.log(error)
    })
}

2:ページを呼び出す

<template>
    <div class="container lzyBox">
      <div class="main-hd">信息发布管理>招商项目>新建</div>

      <div class="main-bd">
          <vue-ueditor-wrap v-model="msg" :config="myConfig"></vue-ueditor-wrap>
          <button >保存</button>
      </div>


      <input
                type="file"
                id="ipa_file-selector"
                :data-dir="app_id"
                data-name="game"
                @change="ipa_selectFile"
              />

    </div>
</template> 
<script type="text/javascript" src="./static/js/cos-js-sdk-v5.min.js"></script> 
<script>
import VueUeditorWrap from 'vue-ueditor-wrap'
import COS  from 'cos-js-sdk-v5'
export default {
  name: 'App',
  components: {
    VueUeditorWrap,
  },
  data () {
    return {
      msg: '<h2><img src="http://img.baidu.com/hi/jx2/j_0003.gif"/>Vue + UEditor + v-model双向绑定</h2>',
      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 240,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 上传文件接口(这个地址是我为了方便各位体验文件上传功能搭建的临时接口,请勿在生产环境使用!!!)
        // serverUrl: 'http://35.201.165.105:8000/controller.php',
        // UEditor 资源文件的存放路径,如果你使用的是 vue-cli 生成的项目,通常不需要设置该选项,vue-ueditor-wrap 会自动处理常见的情况,如果需要特殊配置,参考下方的常见问题2
        UEDITOR_HOME_URL: '/UEditor/'
      },
      app_id:'/src/assets/logo.png'
    }
  },

  computed: {
  },
  methods: {
    onEditorReady(editor) {// 准备编辑器
    },
    onEditorBlur(){// 失去焦点事件
    }, 
    onEditorFocus(){// 获得焦点事件
    }, 
    onEditorChange(){// 内容改变事件
    }, 

    //------------------------------------COS做测试-----------------------------------------
    ipa_selectFile(){
        //console.log(document.getElementById('ipa_file-selector').files[0])
        //这里是给可能会看不懂的同学看的,vue不建议操作DOM,能用ref的用ref。
        var file = document.getElementById('ipa_file-selector').files[0]   
        if (!file) return;
        this.fileCos(file,function(_data){
            console.log(_data)
            // _dom.splice(_l,1,_txt.url);
        })
	    }
  }
}
</script>   

springboot中コントローラー

package com.tengyun.investment.backend.sys.controller;


import com.tengyun.common.model.R;
import com.tengyun.common.utils.FileUploadService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 图片上传工具类
 */
@RestController
@RequestMapping("/fileUpload")
public class FileUploadController {
    @Autowired
    FileUploadService fileUploadService;


    @ApiOperation(value = "获取cos临时签名")
    @GetMapping("/cos/credential")
    R getCredential() {
        return R.ok().put("data",fileUploadService.getCredential());
    }
}

サーブレイヤー

/**
     * 前端上传的临时密钥
     */
    public Map<String, Object> getCredential() {
        TreeMap<String, Object> config = new TreeMap<String, Object>();

//        try {
            config.put("SecretId", secret_id);
            config.put("SecretKey", secret_key);
            // 临时密钥有效时长,单位是秒,默认1800秒,最长可设定有效期为7200秒
            config.put("ExpiredTime", 7200);
//            config.put("bucket", bucketName + "-" + appid);
            config.put("bucket", bucketName);
            config.put("region", regionName);
            // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子:a.jpg 或者 a/* 或者 * 。
            // 如果填写了“*”,将允许用户访问所有资源;除非业务需要,否则请按照最小权限原则授予用户相应的访问权限范围。
            config.put("allowPrefix", "*");

            // 密钥的权限列表。简单上传、表单上传和分片上传需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[]{
                    // 简单上传
                    "name/cos:PutObject",
                    "name/cos:GetObject",
                    "name/cos:DeleteObject",
                    // 表单上传、小程序上传
                    "name/cos:PostObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);
        Map<String, Object> map = null;
        try {
            map = CosStsClient.getCredential(config).toMap();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //成功返回临时密钥信息,如下打印密钥信息
            map.put("keyPrefix", key);
            String bucket = bucketName;
            map.put("bucket", bucket);
            map.put("region", regionName);
            return map;
    }

 

おすすめ

転載: blog.csdn.net/qq_20594019/article/details/114156201