目的:希望在前端上传的头像图片存入云端,然后返回该图片的url给前端更新用户的头像信息
前端: 如何把文件对象传给后端?
1.在表单里编写fileInput
<form @submit.prevent="upload_photo">
<input id="fileInput" type="file" name="file" />
<button type="submit">上传</button>
</form>
2.写一个请求后端的ajax函数
const upload_photo = () => {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
console.log(file)
if (!file) {
error_message.value = "请选择一个文件";
return;
}
const formData = new FormData();
formData.append('file', file);
console.log(formData)
$.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) {
console.log(resp);
error_message.value = "";
if (resp.error_message === "success") {
photo.value = resp.path;
} else {
error_message.value = resp.error_message;
}
}, error() {
}
});
};
后端
1.使用阿里云免费试用3个月的OSS
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c83cddc0ad0b2095e6a4fc6260f39b38.png)
2.创建UpLoadUtil类
package com.edu.mju.backend.config.utils;
import com.aliyun.oss.*;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class UpLoadUtil {
public static final String ALI_DOMAIN = ""
public static Map<String,String> uploadRemote(MultipartFile file) throws IOException {
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;
String endPoint = ""
String accessKeyID = "";
String accessKeySecret ="";
OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyID,accessKeySecret);
ossClient.putObject(仓库名,文件名,文件.getInputStream);
ossClient.shutdown();
resp.put("path",ALI_DOMAIN + fileName);
resp.put("error_message","success");
return resp;
}
}
3.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 UpLoadUtil.uploadRemote(file);
}
4.service层
@Override
public Map<String, String> uploadPhoto(MultipartFile file) {
Map<String,String> resp = new HashMap<>();
if(file.isEmpty()){
resp.put("error_message","上传图片不能为空!");
return resp;
}
String originalFileName = file.getOriginalFilename();
String ext = "." + originalFileName.split("\\.")[1];
String uuid = UUID.randomUUID().toString().replace("-", "");
String newFileName = uuid + ext;
ApplicationHome applicationHome = new ApplicationHome(this.getClass());
String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +"\\src\\main\\resources\\static\\images\\";
System.out.println(pre);
String path = pre + newFileName;
try {
file.transferTo(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
resp.put("error_message","success");
resp.put("path",path);
return resp;
}