zoukankan      html  css  js  c++  java
  • 文件上传

     public void upload (@RequestParam("file") MultipartFile file, String remark) {
            System.out.println("执行了一次");
            // 获取原始名字
            String fileNameOld = file.getOriginalFilename();
            // 获取后缀名
            String suffixName = fileNameOld.substring(fileNameOld.lastIndexOf(".")+1);
            //获取纯文件名
            String onlyFileName = fileNameOld.substring(0,fileNameOld.lastIndexOf("."));
    
            // 文件重命名,防止重复
                 final String OSS_ENDPOINT = "oss-cn-guangzhou.aliyuncs.com";
                 final String OSS_ACCESSKEY = "LTAI4GGAoCDgAvU3bsUhExyN";
                 final String OSS_SECRETKEY = "DDmqUoGIAazHxSGqASqIaAzoaxh6D6";
                 final String OSS_BUCKETNAME = "xiaojie";
            String fileName = UUID.randomUUID() + "_" + fileNameOld;
    
            OSS ossClient = new OSSClientBuilder().build(OSS_ENDPOINT,OSS_ACCESSKEY,OSS_SECRETKEY);
            try {
                final File tempFile = File.createTempFile(UUID.randomUUID() + "_" + onlyFileName,suffixName);
    
                //MultipartFile  转换为 File
                file.transferTo(tempFile);
    
                //容器不存在,就创建
                if(! ossClient.doesBucketExist(OSS_BUCKETNAME)){
                    ossClient.createBucket(OSS_BUCKETNAME);
                    CreateBucketRequest createBucketRequest = new CreateBucketRequest(OSS_BUCKETNAME);
                    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                    ossClient.createBucket(createBucketRequest);
                }
                String fileUrl ="upload/"+ fileName;
    
                PutObjectResult result = ossClient.putObject(new PutObjectRequest(OSS_BUCKETNAME, fileUrl, tempFile));
    
                ossClient.setBucketAcl(OSS_BUCKETNAME, CannedAccessControlList.PublicRead);
    
    
                if(null != result){
                    logger.info("==========>OSS文件上传成功,OSS地址:"+fileUrl);
    
                }
            }catch (OSSException oe){
                logger.error(oe.getMessage());
            }catch (ClientException ce){
                logger.error(ce.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭
                ossClient.shutdown();
            }
        }
    

     文件上传的一个阿里oss的上传使用。

  • 相关阅读:
    UML--->用例图梳理
    UML--->活动图梳理
    论懂产品对程序员的重要性
    markdown时序图语法
    bootstrap 设置表格固定宽度 内容换行
    gitlab的本地搭建和部署使用
    layer.load的使用
    git fatal: remote origin already exists. 报错解决
    导出csv xls文件数字会自动变科学计数法的解决方式
    git常用命令
  • 原文地址:https://www.cnblogs.com/easyjie/p/14680911.html
Copyright © 2011-2022 走看看