Java上传文件到ucloud对象存储上
作者:互联网
使用uclpud对象存储存储文件,比如excel、pdf、png等,这里讲述一下完整的一套使用流程。
官方文档说明:https://github.com/ucloud/ufile-sdk-java
首先在ucloud对象存储中建立存储空间并设置存储空间域名:
创建完毕后进入文件管理,创建需要的文件目录:
然后创建令牌,令牌主要是Java调用的时候用以验证使用:
创建完毕可以查看公钥和私钥。
接下来进行一套流程的代码编写,包括Controller层,service层、web层:
引入pom.xml依赖:
<dependency>
<groupId>cn.ucloud.ufile</groupId>
<artifactId>ufile-client-java</artifactId>
<version>2.4.4</version>
</dependency>
编写Controller层:
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.action.BaseFileAction;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.cms.biz.IUcloudProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller("ucloudUpload")
@RequestMapping("/ucloud")
@Scope("request")
public class UcloudUploadController extends BaseFileAction{
@Autowired
private IUcloudProviderService ucloudProviderService;
@ApiOperation(value = "ucloud上传文件")
@ApiImplicitParams({
@ApiImplicitParam(name = "request", value = "表单信息", required =true,paramType="query"),
})
@LogAnn(title = "上传文件", businessType = BusinessTypeEnum.UPDATE)
@PostMapping("/upload")
@ResponseBody
public ResultData upload(HttpServletRequest req, HttpServletResponse res) throws IOException {
MultipartHttpServletRequest multipartRequest =
(MultipartHttpServletRequest)req;
MultipartFile file = multipartRequest.getFile("file");
String url = ucloudProviderService.upload(file.getInputStream(), file.getContentType(), file.getOriginalFilename());
return ResultData.build().success(url);
}
}
Service层:
import java.io.InputStream;
public interface IUcloudProviderService {
String upload(InputStream inputStream, String mimeType, String fileName);
}
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 net.mingsoft.cms.biz.IUcloudProviderService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.UUID;
@Service
public class UcloudProviderServiceImpl implements IUcloudProviderService {
@Value("${ucloud.ufile.publickey}")
private String publicKey;
@Value("${ucloud.ufile.privatekey}")
private String privateKey;
// bucketName指存储空间,即域名前的那个名称
@Value("${ucloud.bucketName}")
private String bucketName;
public String upload(InputStream inputStream, String mimeType,String fileName){
String newName = "";
String[] split = fileName.split("\\.");
if(split.length>1){
newName =UUID.randomUUID()+"."+split[split.length-1];
}else {
return null;
}
try {
// 这里指创建的目录
String ServerFileName = "test-file/" + newName;
// Bucket相关API的授权器
ObjectAuthorization objectAuthorization = new UfileObjectLocalAuthorization(publicKey,privateKey);
// 对象操作需要ObjectConfig来配置您的地区和域名后缀
ObjectConfig config = new ObjectConfig("cn-sh2", "ufileos.com");
PutObjectResultBean response = UfileClient.object(objectAuthorization, config)
.putObject(inputStream, mimeType)
.nameAs(ServerFileName)
.toBucket(bucketName)
.setOnProgressListener((bytesWritten, contentLength) -> { })
.execute();
if(response!=null && response.getRetCode() == 0 ){
String url = UfileClient.object(objectAuthorization, config)
.getDownloadUrlFromPrivateBucket(ServerFileName, bucketName, 24 * 60 * 60)
.createUrl();
return url;
}else {
return "文件上传失败";
}
} catch (UfileClientException e) {
e.printStackTrace();
return null;
} catch (UfileServerException e) {
e.printStackTrace();
return null;
}
}
}
在yaml文件中配置ucloud令牌信息:
ucloud:
bucketName: test
ufile:
publickey: xxxxxxxxxxxxxxxxxxxx
privatekey: xxxxxxxxxxxxxx
web层:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h4>ucloud上传</h4>
<form action="/ucloud/upload" method="post" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
标签:ucloud,Java,String,springframework,org,import,上传,ufile 来源: https://blog.csdn.net/qq_41061437/article/details/122447037