未分类

上传阿里云对象存储

需求

项目远程调试公司设备时,现场抓取的设备日志是加密的,需要传回来解密排查问题,如果对方电脑没有QQ等可以发送文件软件时,就不太方便。 我的想法就是利用自己的服务器传递文件到自己的阿里云对象存储。利用阿里云CDN可以快速访问文件。

开始

废话不多说直接开始,可参考下方地址

阿里云对象存储快速入门

服务端

添加maven依赖

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<!-- 上传文件 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

spring-mvc配置

1
2
3
4
5
6
7
<!-- 配置文件上传解析器 -->
<!-- id 的值是固定的-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760" />
<property name="maxInMemorySize" value="10485760" />
</bean>

添加oss.properties

1
2
3
4
5
6
7
8
9
#OSS连接路径
endpoint=https://oss-cn-hangzhou.aliyuncs.com
#已经在控制台创建的bucket
bucketName=
#相应的id和key值,请填写你具体的值
accessKeyId=
accessKeySecret=
#前缀,用于创建文件夹
keyPrefix=remote/

创建读取配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SystemConfig {
private static final String CONFIG_PROPERTIES = "oss.properties";

public static String getConfigProperties(String key) throws IOException {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties properties = new Properties();
InputStream in = loader.getResourceAsStream(CONFIG_PROPERTIES);
properties.load(in);
String value = properties.getProperty(key);
value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
in.close();
return value;
}
}

创建OSS配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class OSSConfig {
/**
* OSS连接路径
*/
private String endpoint;
/**
* 需要存储的bucketName
*/
private String bucketName;
/**
* 连接KeyId
*/
private String accessKeyId;
/**
* 连接密钥
*/
private String accessKeySecret;

private String keyPrefix;

public OSSConfig() {
try {
this.endpoint = SystemConfig.getConfigProperties("endpoint");
this.bucketName = SystemConfig.getConfigProperties("bucketName");
this.accessKeyId = SystemConfig.getConfigProperties("accessKeyId");
this.accessKeySecret = SystemConfig.getConfigProperties("accessKeySecret");
this.keyPrefix = SystemConfig.getConfigProperties("keyPrefix");
} catch (IOException e) {
e.printStackTrace();
}
}

public String getEndpoint() {
return endpoint;
}

public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}

public String getBucketName() {
return bucketName;
}

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

public String getAccessKeyId() {
return accessKeyId;
}

public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}

public String getAccessKeySecret() {
return accessKeySecret;
}

public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}

public String getKeyPrefix() {
return keyPrefix;
}

public void setKeyPrefix(String keyPrefix) {
this.keyPrefix = keyPrefix;
}
}

OSS工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@Repository
public class MyOSSUtil {
private static OSSConfig config = null;

/**
* OSS上传文件
*/
public boolean uploadFile(MultipartFile file) {
config = config == null ? new OSSConfig() : config;
OSS ossClient = null;
String fileName = file.getOriginalFilename();
String objectName = config.getKeyPrefix() + UUID.randomUUID() + fileName;
//如果没有下面这两行代码,访问url将不会预览而是直接下载下来
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentType("image/jpg");

try {
ossClient = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
ossClient.putObject(config.getBucketName(), objectName, new ByteArrayInputStream(file.getBytes()));
// String[] url = getUrl(objectName).split("\\?");
// return url[0];
return true;


} catch (IOException e) {
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
// System.out.println(map.toString());
return false;
}

/**
* OSS获取文件列表
*/
public List<OSSObjectSummary> getFileList() {
config = config == null ? new OSSConfig() : config;
OSS ossClient = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());

ObjectListing objectListing = ossClient.listObjects(config.getBucketName(), config.getKeyPrefix());
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
if (null != ossClient) {
ossClient.shutdown();
}
return sums;
}

}

controler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@Controller
@RequestMapping(value = "/zcc")
public class OssController {
private static final Logger logger = Logger.getLogger(OssController.class.getName());

@RequestMapping("/upload.action")
public String uploadFile() {
return "/uploadFile";
}

/***/
@ResponseBody
@RequestMapping("/uploadFile.action")
public Object postData(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
logger.info("request" + request.getRemoteHost());
if (file.isEmpty()) {
Map<String, Object> map = new HashMap<>();
map.put("msg", "上传失败");
map.put("status", "202");
map.put("list", null);
return map;
}
logger.info("fileSize:" + file.getSize());
MyOSSUtil myOssUtil = new MyOSSUtil();
boolean isSuccess = myOssUtil.uploadFile(file);
Map<String, Object> map = new HashMap<>();

if (isSuccess) {
map.put("msg", "上传成功");
map.put("status", "200");
map.put("list", null);
} else {
map.put("msg", "上传失败");
map.put("status", "202");
map.put("list", null);
}
return map;
}


@ResponseBody
@RequestMapping("/getFileList.action")
public Object getFileList(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, Object> map = new HashMap<>();
map.put("msg", "查询成功");
map.put("status", "200");
map.put("list", new MyOSSUtil().getFileList());
return map;
}


}

前端

jsp

1
2
3
4
5
6
7
<body>
<%--文件列表--%>
<ul id="fileArea">
</ul>
选择文件上传<input id="file" type="file">
<button id="save">上传</button>
</body>

js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const URL = "https://zccguagua.oss-cn-hangzhou.aliyuncs.com/";
$(document).ready(function () {
getFileList();


$("#update").click(function () {
console.log("click")
getFileList();
})


//提交
$("#save").click(function () {
//创建表单数据容器
var formData = new FormData()
//获取文件数据
file = $('#file')[0].files[0];
//检查文件上传
if (!file) {
alert('请先上传文件');
return;
}
//添加表单数据
formData.append('file', file);
//得到页面所有表单数据的序列化
// var AllInputData = $("#formData").serializeArray();
// //Array转Object
// AllInputData.forEach(function (e) {
// formData.append(e['name'], e['value']);
// });
//发送请求
$.ajax({
url: "zcc/uploadFile.action",
type: 'post',
data: formData,
contentType: false,
processData: false,
success: function (resp) {
console.log(resp);
if (resp.status == "200") {
alert("上传成功")
} else {
alert(resp.msg)
}
}
})
})


});

function getFileList() {

$("#fileArea").empty();
var urlString = "zcc/getFileList.action";
$.ajax({
url: urlString,
dataType: "json",
data: "",
type: 'get',
success: function (data, textStatus) {
if (data.status == '202') {

alert("出错了!");
return;
}
var ss = data.list;
for (var i = 0; i < ss.length; i++) {
var object = ss[i];
$("#fileArea")
.append(
'<li><a target="_blank" href=' + URL + object.key +
'>' + object.key + '</a></li>'
)
;

}
}
});

}


到此结束,打开网页即可查看文件可直接点击下载,选择文件可以上传

ps:
前端可优化,可增加删除文件,可加拖拽上传

分享到