Ucloud 文件上傳

關注 “弋凡”(YiFan)微信公衆號吧 記錄簡單筆記 做你的最愛

創建一個空間 創建一個令牌

image-20200523171824478.png
image-20200523171835204.png

查看官方文檔說明
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文件
<dependency>
    <groupId>cn.ucloud.ufile</groupId>
    <artifactId>ufile-client-java</artifactId>
    <version>2.4.4</version>
</dependency>
  • 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;
    }

}
  • 上傳頁面編寫
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</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 -

快來關注“弋凡”微信公衆號吧

快來關注“弋凡”微信公衆號把

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章