1.后端
1.创建一个有关阿里云oss操作的工具类AliYunOSS
package com.edu.mju.backend.config.utils;
import com.aliyun.oss.*;
import com.aliyun.oss.model.GetObjectRequest;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class AliYunOSS {
public static final String ALI_DOMAIN = "";
public static final String endPoint = "https://oss-cn-shanghai.aliyuncs.com";
public static final String accessKeyID = "";
public static final String accessKeySecret = "";
public static OSS ossClient = null;
public static Map<String, String> uploadRemote(MultipartFile file) throws IOException {
ossClient = new OSSClientBuilder().build(endPoint, accessKeyID, accessKeySecret);
Map<String, String> resp = new HashMap<>();
String originalFileName = file.getOriginalFilename();
String ext = "." + FilenameUtils.getExtension(originalFileName);
String uuid = UUID.randomUUID().toString().replace("-", "");
String fileName = uuid + ext;
ossClient.putObject("", fileName, file.getInputStream());
ossClient.shutdown();
resp.put("path", ALI_DOMAIN + fileName);
resp.put("error_message", "success");
return resp;
}
public static Map<String, String> DownloadRemote(MultipartFile file) throws IOException {
ossClient = new OSSClientBuilder().build(endPoint, accessKeyID, accessKeySecret);
Map<String, String> resp = new HashMap<>();
String bucketName = "";
String remoteUrl = file.getOriginalFilename();
String localUrl = "C:\\Users\\hasee\\Downloads\\" + remoteUrl;
ossClient.getObject(new GetObjectRequest(bucketName, remoteUrl), new File(localUrl));
ossClient.shutdown();
resp.put("error_message", "success");
return resp;
}
}
2.controller调用工具类即可
@PostMapping("/user/account/upload")
public Map<String,String> upload(@RequestParam("file") MultipartFile file) throws IOException {
String contentType = file.getContentType();
Map<String,String> res = new HashMap<>();
if (!contentType.equals("image/jpeg") && !contentType.equals("image/png")) {
res.put("error_message","只允许上传 JPG 或 PNG 格式的图片文件");
return res;
}
return AliYunOSS.uploadRemote(file);
}
2.前端调用controller
const upload_photo = () => {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
error_message.value = "请选择一个文件";
return;
}
const formData = new FormData();
formData.append('file', file);
$.ajax({
url: "http://127.0.0.1:9090/user/account/upload",
type: "post",
data: formData,
processData: false,
contentType: false,
headers: {
Authorization: "Bearer " + store.state.user.token,
},
success(resp) {
error_message.value = "";
if (resp.error_message === "success") {
show_modal('upload-success');
photo.value = resp.path;
} else {
error_message.value = resp.error_message;
}
}, error() {
}
});
};