0%

电商项目笔记

整合阿里云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
package tech.xixing.machineprice.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tech.xixing.machineprice.service.OssService;
import tech.xixing.machineprice.utils.RandomString;
import tech.xixing.machineprice.vo.ResponseVO;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
* @author xixing
* @version 1.0
* @date 2020/7/11 10:46
*/
@Service
public class OssServiceImpl implements OssService {

@Value("${aliyun.oss.accessKeyId}")
private String ACCESS_KEY_ID;

@Value("${aliyun.oss.accessKeySecret}")
private String ACCESS_KEY_SECRET;

@Value("${aliyun.oss.endpoint}")
private String ENDPOINT;

@Value("${aliyun.oss.bucketName}")
private String BUCKETNAME;


@Override
public ResponseVO<String> uploadFile(MultipartFile file) {
OSS ossClient= new OSSClientBuilder().build(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
String originalFilename = file.getOriginalFilename();
String[] split = originalFilename.split("\\.");

String name = RandomString.getRandomString(15)+"."+split[split.length-1];
try {
ossClient.putObject(BUCKETNAME,"instrument/"+name,new ByteArrayInputStream(file.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
ossClient.shutdown();
String res = StringEscapeUtils.escapeHtml("http://"+BUCKETNAME+"."+ENDPOINT+"/instrument/"+name);
return ResponseVO.successByData(res);
}
}

对于刚生成的id,如果需要用到的话

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
<insert id="insertSelective" parameterType="tech.xixing.machineprice.pojo.Manufactor" useGeneratedKeys="true" keyProperty="id">
insert into manufactor
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
<if test="sortedOrder != null">
sorted_order,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="sortedOrder != null">
#{sortedOrder,jdbcType=INTEGER},
</if>
</trim>
</insert>

useGeneratedKeys=”true” keyProperty=”id”加上这两句,就可以在原来对象中写入这个id。