我們這里是前端將圖片上傳到后端,然后后端這里再上傳到阿里云的OSS,并返回一個(gè)文件的路徑給前端
先看效果

image.png

image.png
<br />
前端:
// pageList.js
const props = {
name: "avatar",
listType: "picture-card",
className: "avatar-uploader",
showUploadList: false,
// 設(shè)置只上傳一張圖片,根據(jù)實(shí)際情況修改
customRequest: info => {
// 手動(dòng)上傳
const formData = new FormData();
formData.append('file', info.file);
uploadLogoImg(formData);
},
onRemove: file => {
// 刪除圖片調(diào)用
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;
}
},
}
...
<Upload
{...props}
>
{logoUrl ? <img src={logoUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
</Upload>
// 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 發(fā)送的參數(shù)');
// console.log(JSON.stringify(params));
return request(`${path}/uploadImage`, {
method: 'POST',
body: params,
});
}
后端:
/**
* 圖片上傳
*/
@PostMapping(value = "uploadImage")
public Response<String> uploadImage(LogoPicReq logoPicReq) {
return success(appservice.uploadLogo(logoPicReq.getFile()));
}
注意:
這里的 LogoPicReq 沒有@RequestBody,因?yàn)檫@里是通過表單提交的
@Data
public class LogoPicReq {
private MultipartFile file;
}
OSS的代碼
if (appFile == null) {
throw new BusinessException("數(shù)據(jù)為空");
}
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("文件為空");
}
//獲取圖片擴(kuò)展名
String ext = filename.substring(filename.lastIndexOf(".") + 1);
//生成圖片的存放在服務(wù)器的路徑
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直鏈]對(duì)象名:{},直鏈地址:{}", picName, signedUrl.toString());
return signedUrl.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
<br />其中一定要通過直聯(lián)的方式進(jìn)行獲取,否則就是上報(bào)沒有權(quán)限<br />
參考:
https://blog.csdn.net/qq_38209894/article/details/99729502