JAVA本地上传文件到OSS服务器
最近需要把文件上传到阿里云服务器,简单记录一下,看了很多文章都没有标出来使用的jar包,首先maven项目在pom文件里添加
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
如果是非maven项目直接在maven库下载,下面是链接
https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss
代码:
package com.springboot.util;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.UUID;
import org.springframework.web.multipart.MultipartFile;
/**
* Created by Administrator on 2016/10/19 0019.
*/
public class UploadImg {
//阿里云API的内或外网域名
private static String ENDPOINT;
//阿里云API的密钥Access Key ID
private static String ACCESS_KEY_ID;
//阿里云API的密钥Access Key Secret
private static String ACCESS_KEY_SECRET;
//阿里云API的bucket名称
private static String BACKET_NAME;
//阿里云API的文件夹名称
// private static String FOLDER;
private static String accessUrl;
static{
ENDPOINT = "oss-cn-beijing.aliyuncs.com";
ACCESS_KEY_ID = "xxxx"; //自己的密钥
ACCESS_KEY_SECRET = "xxx";
BACKET_NAME = "xxx";
accessUrl = "http://lxkcapp.oss-cn-shanghai.aliyuncs.com";
}
public boolean imageUpload(MultipartFile file) throws Exception{
String filename=UUID.randomUUID().toString().replaceAll("-", "");
System.out.println(filename);
Long fileSize=file.getSize();
//创建上传object的metadata
ObjectMetadata metadata=new ObjectMetadata();
metadata.setContentLength(file.getInputStream().available());
metadata.setCacheControl("no-cache");
metadata.setHeader("Pragma", "no-cache");
metadata.setContentEncoding("utf-8");
metadata.setContentType(file.getContentType());
metadata.setContentDisposition("filename/filesize="+filename+"/"+fileSize+"Byte.");
//上传文件
OSSClient client= new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
PutObjectResult putresult=client.putObject(BACKET_NAME,filename, file.getInputStream(),metadata);
System.out.println(putresult.getETag());
Date expiration = new Date(new Date().getTime() + 3600 * 1000);
URL url=client.generatePresignedUrl(BACKET_NAME, filename, expiration);
System.out.println(url.toString());
return true;
}
//获取图片路径
public String getImageURL(String key){
OSSClient client= new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
OSSObject ossObj = client.getObject(BACKET_NAME, key);
Date expiration = new Date(new Date().getTime() + 3600 * 1000);
URL url=client.generatePresignedUrl(BACKET_NAME, key, expiration);
return url.toString();
}
}