阅读背景:

java实现上传图片上传到阿里云

来源:互联网 

近期项目需要上传图片到阿里云,特此记录。

一、引入相应jar包

<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.0</version>
</dependency>

二、在原有项目配置的基础上引用oss相关配置文件:

1、ossclient.properties(填入阿里云oss相关信息)

ossclient.endpoint:https://xxx.aliyuncs.com
ossclient.accessKeyId:xxx
ossclient.accessKeySecret:xxx
ossclient.bucketName:xxx

2、root-oss.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd"

xmlns:context="https://www.springframework.org/schema/context">


<context:property-placeholder
location="classpath*:ossclient.properties" />


<bean id="OssClientServiceImpl" class="com.rongke.oss.service.impl.OssClientServiceImpl">
<property name="bucketName" value="${ossclient.bucketName}"/>
</bean>
<bean id="OSSClientFactory" class="com.rongke.oss.factory.OSSClientFactory">
<property name="endpoint" value="${ossclient.endpoint}"/>
<property name="accessKeyId" value="${ossclient.accessKeyId}"/>
<property name="accessKeySecret" value="${ossclient.accessKeySecret}"/>
</bean>

<bean id="ossClient" factory-bean="OSSClientFactory" factory-method="getOssClient">
</bean>
</beans>

3、spring-applicationContext.xml(记得引入oss的配置文件)

<import resource="classpath*:root-oss.xml"/>

三、相关代码
1、IOssClientService

public interface IOssClientService {
void saveDocument(InputStream inputStream, String key, String contentType, Map<String, String> metadata) throws IOException;

String genUrlFromKey(String key);

String genUrlFromKey(String key, Date date);

InputStream getDocument(String key);
}

2、IOssClientServiceImpl

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.investment.okhttp.builder.GetBuilder;
import com.investment.okhttp.request.RequestCall;
import com.investment.service.IOssClientService;
import com.investment.util.DateUtils;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class OssClientServiceImpl implements IOssClientService {
@Autowired
OSSClient ossClient;

String bucketName;

public void saveDocument(InputStream inputStream, String key, String contentType, Map<String, String> metadata) throws IOException {
ObjectMetadata meta = new ObjectMetadata();
// 设置上传内容类型
meta.setContentType(contentType);
// 上传文件
ossClient.putObject(bucketName, key, inputStream, meta);
}

@Override
public String genUrlFromKey(String key) {
String ret = key;
if (!key.startsWith("http")) {
URL url = ossClient.generatePresignedUrl(bucketName, key, DateUtils.add(DateUtils.now(), Calendar.HOUR_OF_DAY, 1));
ret = url.toString();
}
return ret;
}

@Override
public String genUrlFromKey(String key, Date date) {
String ret = key;
if (!key.startsWith("http")) {
URL url = ossClient.generatePresignedUrl(bucketName, key, date);
ret = url.toString();
}
return ret;
}

@Override
public InputStream getDocument(String key) {
InputStream inputStream = null;
if (!StringUtils.startsWith(key, "http")) {
OSSObject ossObject = ossClient.getObject(bucketName, key);
inputStream = ossObject.getObjectContent();
} else {
GetBuilder builder = new GetBuilder();
builder.url(key);
RequestCall request = builder.build();
try {
Response rep = request.execute();
String re = rep.body().string();
inputStream = new ByteArrayInputStream(re.getBytes());
rep.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return inputStream;
}

public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}

}

3、junit测试

import com.investment.service.IOssClientService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;

@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration({"classpath*:root-oss.xml"}) //加载配置文件
public class OssTest {
@Autowired
IOssClientService ossClientService;

/**
* 测试上传图片
* @throws IOException
*/

@Test
public void testSaveFileToOss2() throws IOException {
File file=new File("D://99jiaeduLogo//logo.png");
byte[] bytes = file2byte(file);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ossClientService.saveDocument(byteArrayInputStream, "starKey", "image/jpeg", null);
}


public byte[] file2byte(File file){
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
} catch (FileNotFoundException ex1) {
ex1.printStackTrace();
} catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
}

/**
* 测试获取上传的图片
* @throws IOException
*/

@Test
public void testGetFile2FromOss() throws IOException {
String url = ossClientService.genUrlFromKey("starKey");
System.out.println(url);
}
}

先运行testSaveFileToOss2()方法,再运行testGetFile2FromOss()方法可以得到一个图片URL,打开URL可以看到刚刚上传的图片。
注意:
有时候是multipartfile(多文件上传),此时需要把multipartfile转为file类型。代码如下:

 public static File multipartToFile(MultipartFile multfile) throws Exception{
CommonsMultipartFile cf = (CommonsMultipartFile)multfile;
//这个myfile是MultipartFile的
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
File file = fi.getStoreLocation();
return file;
}

分享到: