目的
最近需要整合小程序作一个图片上传至阿里云oss存储里。故以此来记录此解决方案。
实践
小程序
本次前端采用的是小程序的lin-ui框架的图片选择器(lin-ui框架不做阐述)
<l-image-picker count="9" bind:linchange="onChangeTap" size="3" id="imagePicker" />
<l-message />
图片上传函数
async wxPostPicture() {
let that = this
const imagePicker = this.selectComponent('#imagePicker');
let urls = imagePicker.linGetValue();
for (let i = 0; i < urls.length; i++) {
wx.uploadFile({
url: "你的图片上传服务地址",
filePath: urls[i],
name: "files",
header: {
"Content-Type": "multipart/form-data",
},
success: function (res) {
let datas = JSON.parse(res.data)
if (datas.code === 200) {
that.data.imgLists.push(datas.data)
that.setData({
imgLists: that.data.imgLists,
})
} else {
wx.lin.showMessage({
content: '上传图片失败'
})
}
}
})
}
}
注意:wx.uploadFile的是采用异步的形式,故需要先统一等待时间,才能获取完整的图片,你可以在调用图片地址之前先sleep一段时间。如下
delay: function (milSec) {
return new Promise(resolve => {
setTimeout(resolve, milSec)
})
},
java后端
依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1.3</version>
</dependency>
配置文件
aliyun:
oss:
file:
endPoint: "你的阿里云oss存储公网地址"
keyid: "在oss中创建用户并创建key"
keysecret: "在oss中创建用户并创建key"
bucketname: "你创建的bucket名字"
参数类
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class OssConstant implements InitializingBean {
@Value("${aliyun.oss.file.endPoint}")
private String oss_file_endpoint;
@Value("${aliyun.oss.file.keyid}")
private String oss_file_keyid;
@Value("${aliyun.oss.file.keysecret}")
private String oss_file_keysecret;
@Value("${aliyun.oss.file.bucketname}")
private String oss_file_bucketname;
public static String OSS_END_POINT_IM;
public static String OSS_BUCKET_IM;
public static String OSS_ACCESS_KEY_ID_IM;
public static String OSS_ACCESS_KEY_SECRET_IM;
@Override
public void afterPropertiesSet() throws Exception {
OSS_END_POINT_IM = oss_file_endpoint;
OSS_BUCKET_IM = oss_file_bucketname;
OSS_ACCESS_KEY_ID_IM = oss_file_keyid;
OSS_ACCESS_KEY_SECRET_IM = oss_file_keysecret;
}
}
上传文件类
import cn.dev33.satoken.stp.StpUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class AliyunOSSUtil {
private static final String accessKeyId = OssConstant.OSS_ACCESS_KEY_ID_IM;
private static final String accessKeySecret = OssConstant.OSS_ACCESS_KEY_SECRET_IM;
private static final String endpoint = OssConstant.OSS_END_POINT_IM;
private static final String bucket = OssConstant.OSS_BUCKET_IM;
private static final String tag = "oss图片路径的参数,例如水印等参数,自行查询";
private static final Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
public static String OSSUploadFile(MultipartFile file) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd : hh:mm:ss");
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
if (!ossClient.doesBucketExist(bucket)) {
ossClient.createBucket(bucket);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
createBucketRequest.setCannedACL(CannedAccessControlList.Default);
ossClient.createBucket(createBucketRequest);
}
String fileUrl = "img" + "/" + StpUtil.getLoginId() + "-" + format.format(new Date()) + "-" + file.getOriginalFilename();
PutObjectResult result = null;
try {
result = ossClient.putObject(new PutObjectRequest(bucket, fileUrl, new ByteArrayInputStream(file.getBytes())));
} catch (IOException e) {
e.printStackTrace();
}
ossClient.setBucketAcl(bucket, CannedAccessControlList.PublicRead);
if (null != result) {
logger.info("==========>OSS文件上传成功,OSS地址:" + fileUrl);
return "fileUrl + tag;
}
} catch (OSSException oe) {
logger.error(oe.getMessage());
} catch (ClientException ce) {
logger.error(ce.getMessage());
} finally {
ossClient.shutdown();
}
return null;
}
}
controller类
@RestController()
@RequestMapping("/test")
public class TbCommonController {
@PostMapping(value = "picture/url/get")
TbResult getPictureUrl(@RequestParam("files") MultipartFile files) {
String url = AliyunOSSUtil.OSSUploadFile(files);
return TbResult.success(url,"ok");
}
}
总结
后端借鉴一篇博客,但找不到出处了,在此说明一下。 为了下次方便使用,仅以此来作记录。
|