上传文件到腾讯存储桶

1、前端

a.form 表单的提交方式必须为 post
b.enctype 属性需要修改为:multipart/form-data
c.必须有一个 type 属性为 file 的 input 标签,其中需要有一个 name 属性;如果需要
上传多个文件需要添加 multiple 属性
 <input id="importFile" style="width: 200px" type="file"/>
            var importFile = $('#importFile').val();

            isFile = '0';
                var fileType = importFile.substr(importFile.lastIndexOf('.') + 1, importFile.length).toLowerCase();
                if (fileType != 'xls' && fileType != 'xlsx') {
                    confirm_show(giftCertificate_problem_point, boss_system_pleaseUploadCorrectFile);
                    return;
                }
                var formData = new FormData();
                var file = document.getElementById('importFile');
                formData.append('importFile', file.files[0]);
                $.ajax({
                    url: contextPath + '/gc/importFile',
                    type: 'post',
                    data: formData,
                    dataType: "json",
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (result) {
                        if (result != null && result != '') {
                            if (result.info.length == 0) {
                                confirm_show(giftCertificate_problem_point, giftCertificate_success_importFail);
                                return;
                            }
                            if (result.code == '1') {
                                assignPersonInfo = '';
                                for (i in result.info) {
                                    if (assignPersonInfo == '') {
                                        assignPersonInfo += result.info[i];
                                    } else {
                                        assignPersonInfo += ',' + result.info[i];
                                    }
                                }

                            } else if ('cf' == result.code) {
                                confirm_show(giftCertificate_problem_point, result.info);
                                return;
                            } else {
                                confirm_show(giftCertificate_problem_point, giftCertificate_success_importFail);
                                return;
                            }
                        }
                    }, error: function () {
                        confirm_show(giftCertificate_problem_point, giftCertificate_success_importFail);
                        return;
                    }
                });

2、配置文件(配置腾讯存储桶的信息)

tencent:
  bucket:
    SecretId: "AKIDq2T*************5PqO2nebiwFnoIGK"
    SecretKey: "S77Ec9*************04EJNf6h"
    Bucket: 'fms-*******1282'
    Region: 'a*****jing'
    upload: 
      preffix-url: https://fms-ad2-t********82.cos.ap-beijing.myqcloud.com
    url: /boss2/

将配置文件注入到bean中

@Data
@Configuration
@ConfigurationProperties(prefix = "tencent.bucket")
public class TencentCosConfig {
  private String SecretId;
  private String SecretKey;
  private String url;
  private String Bucket;
  private String Region;
  private Map<String,String> upload=new HashMap<>();
}

引入腾讯存储桶的依赖(gradle为例) 

compile group: 'com.qcloud', name: 'cos_api', version: '5.6.8'

 集成腾讯存储桶的api

@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TencentCosUtil {
  private final TencentCosConfig cosConfig;

  /**
   * 腾讯云COSClient创建
   *
   * @return
   */
  public COSClient createCOSClient() {

    // 实例化一个认证对象
    COSCredentials cosCredentials = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
    // 设置bucket区域
    Region region = new Region(cosConfig.getRegion());
    ClientConfig clientConfig = new ClientConfig(region);
    // 生成cos客户端
    return new COSClient(cosCredentials, clientConfig);
  }

  /**
   * 腾讯云对象上传
   * @param cosClient
   * @param file
   * @param fileKey url
   */
  public boolean putObject(COSClient cosClient, File file, String fileKey) {

    String methodName = "put object";
    boolean result = false;
    log.info("{}, file name: {}, file key: {}", methodName, file.getName(), fileKey);
    try {
      // 上传
      PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucket(), fileKey, file);
      cosClient.putObject(putObjectRequest);
      result = true;
    } catch (Exception ex) {
      log.error("{}, file name: {}, file key: {}, error: ", methodName, file.getName(), fileKey, ex);
    }
    return result;
  }

  /**
   * 腾讯云存储桶分块上传
   *
   * @param cosClient
   * @param fileUrl
   * @param fileKey
   */
  public void uploadPartObject(COSClient cosClient, String fileUrl, String fileKey) {

    String methodName = "upload part object";
    log.info("{}, file url: {}, file key: {}", methodName, fileUrl, fileKey);

    PutObjectResult putObjectResult = null;
    try {
      // 指定上传文件
      File uploadFile = new File(fileUrl);
      // 创建线程池
      ExecutorService threadPool = Executors.newFixedThreadPool(8);
      // 传入一个 threadpool, 若不传入线程池, 默认 TransferManager 中会生成一个单线程的线程池。
      TransferManager transferManager = new TransferManager(cosClient, threadPool);
      //分装与上传
      PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucket(), fileKey, uploadFile);
      Upload upload = transferManager.upload(putObjectRequest);
      // 等待传输结束(如果想同步的等待上传结束,则调用 waitForCompletion)
      upload.waitForUploadResult();
      // 关闭 TransferManger
      transferManager.shutdownNow();

    } catch (Exception ex) {
      log.error("{}, file url: {}, file key: {}, error: ", methodName, fileUrl, fileKey, ex);
    }
  }

  /**
   * 腾讯云存储对象元数据获取
   *
   * @param cosClient
   * @param bucketName
   * @param fileKey
   * @return
   */
  public ObjectMetadata getObjectMetadata(COSClient cosClient, String bucketName, String fileKey) {
    return cosClient.getObjectMetadata(cosConfig.getBucket(), fileKey);
  }
}

3、使用


@AutoWired
private TencentCosUtil cosUtil;
@AutoWired
private TencentCosConfig cosConfig;



 /**
   * 上传图片
   *
   * @param request
   * @param response
   * @param session
   * @param upload
   */
  public Map<String, Object> uploadImage(HttpServletRequest request, HttpServletResponse response, HttpSession session, MultipartFile[] upload) {
    response.setCharacterEncoding("UTF-8");
//    是否成功
    int isSuccess = WebsiteConstant.FAILED;
    // 获得response,request
    Map<String, Object> m = new HashMap<String, Object>();

    if (!ServletFileUpload.isMultipartContent(request)) {
      m.put("error", 1);
      m.put("message", "请选择文件!");
      log.info("请选择文件!");
      return m;
    }

    String originalFileName = null;//上传的图片文件名
    String fileExtensionName = null;//上传图片的文件扩展名
    if (1 < upload.length) return m;
    MultipartFile file = upload[0];
    if (file.getSize() > 50 * 1024 * 1024) {
      m.put("error", 1);
      m.put("message", "文件过大!");
      log.info("文件过大!");
      return m;

    }

    originalFileName = file.getOriginalFilename();
    log.info("上传的图片文件名=" + originalFileName);
    fileExtensionName = originalFileName.substring(
            originalFileName.lastIndexOf(".")).toLowerCase();
    log.info("图片文件扩展名=" + fileExtensionName);

    String[] imageExtensionNameArray = WebsiteConstant.IMAGE_EXTENSION_NAME_ARRAY;

    boolean isContain = false;//默认不包含上传图片文件扩展名
    for (int i = 0; i < imageExtensionNameArray.length; i++) {
      if (fileExtensionName.equals(imageExtensionNameArray[i])) {
        isContain = true;
      }
    }

    String newFileName = UUID.randomUUID() + fileExtensionName;
    String imageUrl = "";
//    String uploadPath;
//    if ((!System.getProperties().getProperty("os.name").toLowerCase().contains("linux"))) {
//      uploadPath = WebsiteConstant.PIC_APP_FILE_SYSTEM_CKEDITOR_LOCATION;
//    } else {
//      uploadPath = WebsiteConstant.PIC_APP_FILE_SYSTEM_CKEDITOR_SERVICE;
//    }
    if (isContain) {//包含
//      File pathFile = new File(uploadPath);
//      if (!pathFile.exists()) { // 如果路径不存在,创建
//        pathFile.mkdirs();
//      }
      try {
//        生成临时文件
        String[] split = originalFileName.split("\\.");

        File f = File.createTempFile(split[0], split[1]);
        file.transferTo(f);
//        上传到存储桶
        cosUtil.putObject(cosUtil.createCOSClient(), f, cosConfig.getUrl() + newFileName);
//        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(uploadPath, newFileName));
      } catch (IOException e) {
        log.error(" newFileName =" + newFileName + " exception=" + e);
      }//http://127.0.0.1:8383/
      imageUrl = /*"http://"+bossConfig.getIP()+":8383/images/editor/" */
              cosConfig.getUpload().get("preffix-url") + cosConfig.getUrl() + newFileName;
      isSuccess = WebsiteConstant.SUCCESS;

    } else {
      m.put("error", 1);
      m.put("message", "请上传图片文件!");
      log.info("请上传图片文件!");
      return m;
    }
    m.put("uploaded", isSuccess);
    m.put("fileName", newFileName);
    m.put("url", imageUrl);
    return m;
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值