文件上传

 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的上传使用。

文件上传

上一篇:JS判断H5运行环境


下一篇:分享一些关于网站安全的知识点