Ucloud 文件上传

关注 “弋凡”(YiFan)微信公众号吧 记录简单笔记 做你的最爱

创建一个空间 创建一个令牌

Ucloud 文件上传_第1张图片
Ucloud 文件上传_第2张图片

查看官方文档说明
https://github.com/ucloud/ufile-sdk-java

上传文件

File file = new File("your file path");

try {
    PutObjectResultBean response = UfileClient.object(Constants.OBJECT_AUTHORIZER, config)
         .putObject(file, "mimeType")
         .nameAs("save as keyName")
         .toBucket("upload to which bucket")
         /**
          * 是否上传校验MD5, Default = true
          */
     //  .withVerifyMd5(false)
         /**
          * 指定progress callback的间隔, Default = 每秒回调
          */
     //  .withProgressConfig(ProgressConfig.callbackWithPercent(10))
         /**
          * 配置进度监听
          */
         .setOnProgressListener(new OnProgressListener() {
              @Override
              public void onProgress(long bytesWritten, long contentLength) {
                  
              }
         })
         .execute();
} catch (UfileClientException e) {
    e.printStackTrace();
} catch (UfileServerException e) {
    e.printStackTrace();
}

案例

  • 导入pom文件

    cn.ucloud.ufile
    ufile-client-java
    2.4.4

  • application.properties 编写
#  ucloud  你创建的令牌 以及你的空间名
ucloud.ufile.publickey=TOKEN_xfd2a2-6fx8-4c6c-8af6-502x966x8xxxx
ucloud.ufile.privatekey=1e077ax2-a923-4a1x-bbea-9x2d8x32xxxx
ucloud.bucketName=zfan
  • UcloudProvider 编写
import cn.ucloud.ufile.UfileClient;
import cn.ucloud.ufile.api.object.ObjectConfig;
import cn.ucloud.ufile.auth.ObjectAuthorization;
import cn.ucloud.ufile.auth.UfileObjectLocalAuthorization;
import cn.ucloud.ufile.bean.PutObjectResultBean;
import cn.ucloud.ufile.exception.UfileClientException;
import cn.ucloud.ufile.exception.UfileServerException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

@Service
public class UcloudProvider {

    @Value("${ucloud.ufile.publickey}")
    private String publicKey;
    @Value("${ucloud.ufile.privatekey}")
    private String privateKey;
    @Value("${ucloud.bucketName}")
    private String bucketName;


    public String upload(InputStream inputStream, String mimeType,String fileName){
            File file = new File("your file path");
            String newName = "";
            String[] split = fileName.split("\\.");
            if(split.length>1){
                newName =UUID.randomUUID()+"."+split[split.length-1];
            }else {
                return null;
            }

            try {
                // Bucket相关API的授权器
                ObjectAuthorization objectAuthorization = new UfileObjectLocalAuthorization(publicKey,privateKey);
                // 对象操作需要ObjectConfig来配置您的地区和域名后缀
                ObjectConfig config = new ObjectConfig("cn-bj", "ufileos.com");
                bucketName = "zfan";
                PutObjectResultBean response = UfileClient.object(objectAuthorization, config)
                        .putObject(inputStream, mimeType)
                        .nameAs(newName)
                        .toBucket(bucketName)
                        .setOnProgressListener((bytesWritten, contentLength) -> { })
                        .execute();

              if(response!=null && response.getRetCode() == 0 ){
                 String url = UfileClient.object(objectAuthorization, config)
                     .getDownloadUrlFromPrivateBucket(newName, bucketName, 24 * 60 * 60)
                                    .createUrl();
                            return url;
                        }else {
                            return "文件上传失败";
                        }
        } catch (UfileClientException e) {
            e.printStackTrace();
            return null;
        } catch (UfileServerException e) {
            e.printStackTrace();
            return null;
        }
    }
}

  • controller编写
// file.getOriginalFilename()是得到上传时的文件名
// file.getContentType()文件类型
@RestController
public class UploadController {
    @Autowired
    private UcloudProvider ucloudProvider;

    @RequestMapping("upload")
    public String upload(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest =  
            (MultipartHttpServletRequest)request;
        MultipartFile file = multipartRequest.getFile("file");
        String upload = ucloudProvider.upload(file.getInputStream(), file.getContentType(), file.getOriginalFilename());
        return upload;
    }

}
  • 上传页面编写

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

<h4>首页h4>
<form action="/upload" method="post" enctype="multipart/form-data">
    <p><input type="file" name="file">p>
    <p><input type="submit" value="提交">p>
form>

body>
html>

end -

快来关注“弋凡”微信公众号吧

Ucloud 文件上传_第3张图片

你可能感兴趣的:(笔记)