1.前端代码
javascript
<template>
<div>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">上传头像</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
};
},
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
},
async uploadFile() {
if (!this.file) {
alert('请选择一个文件');
return;
}
const formData = new FormData();
formData.append('file', this.file);
try {
const response = await axios.post('/AccountAvatar', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
if (response.data.success) {
alert('文件上传成功');
console.log('上传成功', response.data);
} else {
alert('文件上传失败: ' + response.data.message);
}
} catch (error) {
console.error('上传失败', error);
alert('上传失败: ' + error.message);
}
},
},
};
</script>
2.后端代码
java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "文件为空";
}
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 将文件保存到服务器上的某个目录
File dest = new File("/path/to/save/" + fileName);
file.transferTo(dest);
return "文件上传成功";
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败";
}
}
}