Vue elementUI uploads files to OSS server, backend (java) (with pictures and text)

OSS configuration


First go to the official website of Alibaba Cloud, activate and configure the OSS service

Enter the object storage OSS and create a Bucket ( record the Endpoint, which will be used when the back-end configuration connects to OSS )

Test whether the uploaded file is available in the newly created Bucket

Go to Alibaba Cloud's access control to create a new sub-user

Notice:

Remember to copy the AccessKey ID and AccessKey Secret when the sub-user is successfully created

and save it, otherwise the information cannot be obtained after exiting. Only new subusers can be recreated.

After the creation is complete, add permissions for the sub-user

At this point, the OSS service is activated.

backend configuration


Next is the configuration of the java backend and the connection to the OSS server.

pom.xml add the following dependencies

<aliyun.oss.version>3.8.0</aliyun.oss.version>
<jodatime.version>2.10.1</jodatime.version>
<!--日期时间工具-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>${jodatime.version}</version>
</dependency>
<!--aliyunOSS-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>${aliyun.oss.version}</version>
</dependency>

Configure OSS properties in the configuration file application.yaml

config:
  oss:
    endpoint: oss-cn-hangzhou.aliyuncs.com
    keyid: 存放前面创建子用户的参数AccessKey ID
    keysecret: 存放前面创建子用户的参数AccessKey Secret 
    #bucket可以在控制台创建,也可以使用java代码创建
    bucketname: 存放所创建的Bucket名称

Next create the configuration class

@Data
@Component
@ConfigurationProperties(prefix="config.oss")
publicclassOssConfig {
    privateStringendpoint;
    privateStringkeyid;
    privateStringkeysecret;
    privateStringbucketname;
}

Add the implementation class of service

@Service
publicclassFileServiceImpl{
    @Autowired
    privateOssConfigossConfig;
    
    publicStringupload(InputStreaminputStream, Stringmodule, StringoriginalFilename) {
        // 获得oss 服务器的信息
        Stringendpoint=ossConfig.getEndpoint();
        Stringkeyid=ossConfig.getKeyid();
        Stringkeysecret=ossConfig.getKeysecret();
        Stringbucketname=ossConfig.getBucketname();
        //判断oss实例是否存在:如果不存在则创建,如果存在则获取
        OSSossClient=newOSSClientBuilder().build(endpoint, keyid, keysecret);
        if (!ossClient.doesBucketExist(bucketname)) {
            //创建bucket
            ossClient.createBucket(bucketname);
            //设置oss实例的访问权限:公共读
            ossClient.setBucketAcl(bucketname, CannedAccessControlList.PublicRead);
        }
        //构建日期路径:avatar/2020/08/11/文件名
        Stringfolder=newDateTime().toString("yyyy/MM/dd");
        //文件名:uuid.扩展名
        StringfileName=UUID.randomUUID().toString();
        StringfileExtension=originalFilename.substring(originalFilename.lastIndexOf("."));
        Stringkey=module+"/"+folder+"/"+fileName+fileExtension;
        //文件上传至阿里云
        ossClient.putObject(ossConfig.getBucketname(), key, inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
        //返回url地址
        return"https://"+bucketname+"."+endpoint+"/"+key;
    }
}

final test

@ApiOperation("文件上传")
@PostMapping("/upload")
publicRupload(
        @ApiParam(value="文件", required=true)
        @RequestParam("file") MultipartFilefile,
        @ApiParam(value="模块", required=true)
        @RequestParam("module") Stringmodule) throwsIOException {
    // 获得上传文件的 InputStream
    InputStreaminputStream=file.getInputStream();
    // 获得上传文件的名字
    StringoriginalFilename=file.getOriginalFilename();
    StringuploadUrl=fileService.upload(inputStream, module, originalFilename);
    //返回r对象
    returnnewR(ResponseEnum.SUCCESS,uploadUrl);
}

Test on swagger

At this point, the backend test is completed.

Front-end configuration


The front end is implemented with vue

// 文件上传组件
// http://localhost:8100/upload?module=avatar 路径为后端上传文件的接口
<el-uploadclass="avatar-uploader"action="http://localhost:8100/upload?module=avatar"
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
          <imgv-if="imageUrl"
               :src="imageUrl"
               class="avatar">
          <iv-else
             class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
    // method中的方法
    // 上传成功后
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    // 可能URL.createObjectURL(file.raw);会出现路径错误
    // 可以替换为:this.imageUrl = res.data;
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 <2;
      if(!isJPG){
        this.$message.error('上传头像图片只能是 png 格式!');
      }
      if(!isLt2M){
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      returnisJPG&&isLt2M;
    },

At this point, elementUI uploading files to the OSS server is basically completed.

Remember to like, collect, follow!

Guess you like

Origin blog.csdn.net/ILIKETANGBOHU/article/details/129039313