我们这里是前端将图片上传到后端,然后后端这里再上传到阿里云的OSS,并返回一个文件的路径给前端
先看效果
上传后生成的图片
前端:
// pageList.js
const props = {
name: "avatar",
listType: "picture-card",
className: "avatar-uploader",
showUploadList: false,
// 设置只上传一张图片,根据实际情况修改
customRequest: info => {
// 手动上传
const formData = new FormData();
formData.append('file', info.file);
uploadLogoImg(formData);
},
onRemove: file => {
// 删除图片调用
this.setState(state => {
const index = state.fileList.indexOf(file);
const newFileList = state.fileList.slice();
newFileList.splice(index, 1);
return {
fileList: newFileList,
};
});
},
beforeUpload: file => {
// 控制上传图片格式
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('您只能上传JPG/PNG 文件!');
return;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片大小必须小于2MB!');
return;
}
},
}
...
{logoUrl ? : uploadButton}
// model.js
// 上传图片logo
*uploadLogoImg({ payload }, { call, put }) {
const response = yield call(uploadLogoImg, payload);
yield put({
type: 'handleUploadLogoImg',
payload: {
response
},
});
},
// api.js
export async function uploadLogoImg(params) {
// console.log('cityApi.pageList 发送的参数');
// console.log(JSON.stringify(params));
return request(`${path}/uploadImage`, {
method: 'POST',
body: params,
});
}
后端:
/**
* 图片上传
*/
@PostMapping(value = "uploadImage")
public Response uploadImage(LogoPicReq logoPicReq) {
return success(appservice.uploadLogo(logoPicReq.getFile()));
}
注意:
这里的 LogoPicReq
没有@RequestBody,因为这里是通过表单提交的
@Data
public class LogoPicReq {
private MultipartFile file;
}
OSS的代码
if (appFile == null) {
throw new BusinessException("数据为空");
}
String endpoint = ossProperties.getEndpoint();
String accessKeyId = ossProperties.getAccessKeyId();
String accessKeySecret = ossProperties.getAccessKeySecret();
String bucketName = ossProperties.getBucketName();
InputStream fileContent;
try {
fileContent = appFile.getInputStream();
//获取图片名称
String filename = appFile.getOriginalFilename();
if (null == filename || "".equals(filename)) {
throw new BusinessException("文件为空");
}
//获取图片扩展名
String ext = filename.substring(filename.lastIndexOf(".") + 1);
//生成图片的存放在服务器的路径
String picName = "img/walle/" + UUID.randomUUID().toString() + "." + ext;
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, picName, fileContent);
ossClient.shutdown();
//获取OSS生成的url
Date date = new Date();
date.setTime(date.getTime() + 100L * 365 * 24 * 3600 * 1000);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, picName, HttpMethod.GET);
request.setExpiration(date);
URL signedUrl = ossClient.generatePresignedUrl(request);
log.info("[生成OSS直链]对象名:{},直链地址:{}", picName, signedUrl.toString());
return signedUrl.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
其中一定要通过直联的方式进行获取,否则就是上报没有权限
参考:
https://blog.csdn.net/qq_38209894/article/details/99729502
参考2
https://qdhaiqiang.github.io/2019/03/14/Ant%20Design%20Pro%E5%AD%A6%E4%B9%A0%E4%B9%8B%E4%BD%BF%E7%94%A8upload%E7%BB%84%E4%BB%B6%E5%B9%B6%E7%94%A8form%E8%A1%A8%E5%8D%95%E6%8F%90%E4%BA%A4/