传统服务器文件保存迁移阿里云OSS遇到的问题
1.文件上传
直接使用阿里云官方的工具上传即可;
需要注意的地方,抽取方法工具类时,要把文件在OSS里的地址作为返回值返回;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.File;
public class Demo {
public static void main(String[] args) throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
String objectName = "exampledir/exampleobject.txt";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
String filePath= "D:\\localpath\\examplefile.txt";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, filePath);
// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// 上传文件。
ossClient.putObject(putObjectRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
2.文件下载出现的问题
使用阿里云官方下载工具,不能指定File
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = "yourEndpoint";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填写Bucket名称。
String bucketName = "examplebucket";
// 填写不包含Bucket名称在内的Object完整路径,例如testfolder/exampleobject.txt。
String objectName = "testfolder/exampleobject.txt";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
// 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File("D:\\localpath\\examplefile.txt")); //这里有bug,不能指定File地址
// 关闭OSSClient。
ossClient.shutdown();
解决方法:
//创建出来文件夹
File temp = new File(fileConfig.getTmpPath());
File file= new File(fileConfig.getTmpPath()+entity.getFileName());
if (!temp.exists()){
temp.mkdirs();
}
//获得objectName
String[] split = entity.getFilePath().split("yc/");
String objectName = split[1];
OSS ossClient = OssUtil.getOssClient();
try (FileOutputStream fos = new FileOutputStream(file)){
// 下载OSS文件流
OSSObject object = ossClient.getObject("bucket名字", objectName);
InputStream is = object.getObjectContent();
byte[] b = new byte[1024];
int length;
while((length= is.read(b)) != -1){
fos.write(b,0,length);
}
is.close();
// 关闭OSSClient。
ossClient.shutdown();
}catch (Exception e){
log.warn(e.getMessage());
}
3.阿里云在线查看文件的方法
BufferedOutputStream toClient = null;
InputStream fis = null;
try {
toClient = new BufferedOutputStream(response.getOutputStream());
URL u = new URL(archiveOriginal.getFilePath());
HttpURLConnection urlconn = (HttpURLConnection) u.openConnection();
urlconn.setDoInput(true);
urlconn.setConnectTimeout(60000);
urlconn.setReadTimeout(60000);
urlconn.connect();
fis = urlconn.getInputStream();
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "application/pdf");
response.setContentType(urlconn.getContentType());
byte[] buffer = new byte[1024 * 1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
toClient.write(buffer, 0, len);
}
toClient.flush();
} catch (Exception e) {
log.warn(e.getMessage());
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
log.warn(e.getMessage());
}
}
if (toClient != null) {
try {
toClient.close();
} catch (IOException e) {
log.warn(e.getMessage());
}
}
}