当前位置:   article > 正文

springboot腾讯云文件上传_java后端文件上传 腾讯云

java后端文件上传 腾讯云
一、引入依赖
<dependency>
     <groupId>com.qcloud</groupId>
     <artifactId>cos_api</artifactId>
     <version>5.6.24</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
二、后台代码
package com.admin.controller;

import com.admin.util.CommonUtil;
import com.admin.util.Result;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * 腾讯云对象存储文件上传API
 *
 * @author: wangghua
 * @version: 1.0
 * @date: 2020-11-18 15:00
 **/
@RestController
@RequestMapping(value = "/tengxun")
@Api(tags = "后台-腾讯云文件上传")
public class UploadTXController {
    private String secretId="你的腾讯云secretId";     				//腾讯云对象存储的secretId(需替换)
    private String secretKey="你的腾讯云secretKey";          			//腾讯云对象存储的secretKey(需替换)
    private String bucket="ap-chengdu";                             //所属地域
    private String bucketName="你的存储桶名称";                       //存储桶名称(需替换)
    private String path="https://bucketName.coscd.myqcloud.com";    //访问域名(bucketName替换为你的存储桶名称)
    private String qianzhui="directory";      						//上传目录(需替换)

    /**
     * 上传到腾讯云服务器(https://cloud.tencent.com/document/product/436/10199)
     *
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Object Upload(@RequestParam(value = "file") MultipartFile file, HttpSession session) {
        if (CommonUtil.isEmpty(file)) {
            return new Result(Result.Code.FAILED,"文件不能为空!");
        }
        String oldFileName = file.getOriginalFilename();
        String eName = oldFileName.substring(oldFileName.lastIndexOf(".")); //获取文件后缀
        String newFileName = UUID.randomUUID() + eName; //文件名
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(bucket));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
        String bucketName = this.bucketName;

        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
        // 大文件上传请参照 API 文档高级 API 上传
        File localFile = null;
        try {
            localFile = File.createTempFile("temp", null);
            file.transferTo(localFile);
            // 指定要上传到 COS 上的路径
            String key = "/" + this.qianzhui + "/"  + newFileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            Map<String, Object> data = new HashMap<>();
            data.put("url",this.path + putObjectRequest.getKey());
            data.put("code", 200);
            data.put("msg", "成功");
            data.put("size", file.getSize());
            return data;
        } catch (IOException e) {
            return new Result(Result.Code.FAILED,e.getMessage());
        } finally {
            // 关闭客户端(关闭后台线程)
            cosclient.shutdown();
        }
    }


}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
以下是后端返回数据封装类Result
package com.admin.util;

import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
@ApiModel(description= "返回响应数据")
@Data
public class Result implements Serializable {


    private static final long serialVersionUID = 6230939589190169253L;

    public enum Code{
        SUCCESS(0, "成功"),
        SYSTEMERROR(1001, "系统出了点小bug,请联系开发人员"),
        REQUESTERROR(1002, "请求错误"),
        FAILED(1003, "失败"),
        SIGNERROR(1004, "签名错误"),
        PARAMERROR(1005, "参数错误"),
        ROLEBAN(1006,"权限不足"),
        UNIQUECONSTRAINTERROR(1007, "数据唯一属性冲突"),
        AUTHERROR(1008, "数据唯一属性冲突"),
        NEEDLOGIN(1009,"需要登录");
        private int code;
        private String errorMessage;



        private Code(int code, String errorMessage) {
            this.code = code;
            this.errorMessage = errorMessage;
        }

        @JsonValue
        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getErrorMessage() {
            return errorMessage;
        }

        public void setErrorMessage(String errorMessage) {
            this.errorMessage = errorMessage;
        }
    }

    @ApiModelProperty(value = "响应状态码")
    private Code code;
    @ApiModelProperty(value = "响应信息")
    private String message;
    @ApiModelProperty(value = "响应数据")
    private Object data;
    @ApiModelProperty(value = "响应数据条数")
    private long count;
    public void setMessage(String message) {
        this.message = message;
    }
    public long getCount() {
        return count;
    }



    public void setCount(long count) {
        this.count = count;
    }
    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public Code getCode() {
        return code;
    }

    public void setCode(Code code) {
        this.code = code;
        this.message=code.getErrorMessage();
    }

    public Result() {

    }

    public Result(Code code, String message) {
        this.code = code;
        this.message = message;
    }

    public Result(Code code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public void setMessage(Code code, String message) {
        this.code = code;
        this.message = message;
    }

    public void setMessage(Code code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
下面这是引用的CommonUtil
package com.admin.util;
import java.util.Collection;
import java.util.Map;
public class CommonUtil {
/**
	 * 判断是否为空
	 * @param obj Object
	 * @return 空 = true,不为空 = false
	 */
	public static boolean isEmpty(Object obj) {
		if (obj == null) {
			return true;
		} else if (obj instanceof String && (obj.equals("") )) {
			return true;
		} else if (obj instanceof Boolean && !((Boolean) obj)) {
			return true;
		} else if (obj instanceof Collection && ((Collection<?>) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Map && ((Map<?,?>) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Object[] && ((Object[]) obj).length == 0) {
			return true;
		}
		if("null".equals(obj)){
			return true;
		}
		return false;
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

注:如项目中没有使用swagger2作为系统接口文档,删掉代码里面的几个注解(@ApiModel,@ApiModelProperty,@Api)就可以了

前端请求代码根据项目所需请求接口,此处便不贴代码了
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/346793
推荐阅读
相关标签
  

闽ICP备14008679号