博主在后端自定义了接口:
@PostMapping("/upload") public AjaxResult upload(@RequestPart("file") MultipartFile file, @RequestParam("studentId") String studentId, @RequestParam("thesisTitle") String thesisTitle, @RequestParam("thesisKeywords") String thesisKeywords) { try { TbThesis thesis = new TbThesis(); thesis.setThesisTitle(thesisTitle); thesis.setThesisKeywords(thesisKeywords); thesis.setStudentId(studentId); String url = tbThesisService.uploadThesis(file, thesis); Map<String, String> data = new java.util.HashMap<>(); data.put("url", url); return AjaxResult.success("上传成功", data); } catch (Exception e) { return AjaxResult.error(e.getMessage()); } }但是前端调用ajax请求却报错404,经过仔细排查,发现是因为在 RuoYi-Vue 的前端工程里,“裸” ajax(axios)404、跨域、认证失败、统一错误处理全都没有了。不经过vite转发不会到后端8080端口。
应当在api/system目录下注册js代码
import request from '@/utils/request' export function uploadThesis(data) { return request({ url: '/system/thesis/upload', method: 'post', data, headers: { 'Content-Type': 'multipart/form-data' } }) }然后,前端页面直接调用封装方法:
const fd = new FormData() fd.append('file', file.value) fd.append('thesisTitle', form.thesisTitle) fd.append('thesisKeywords', form.thesisKeywords) fd.append('studentId', form.studentId) loading.value = true try { const { msg } = await uploadThesis(fd) // 2. 直接调用封装方法 ElMessage.success(msg || '上传成功') // 成功后重置 uploadRef.value.clearFiles() Object.assign(form, { thesisTitle: '', thesisKeywords: '', studentId: '' }) } catch (e) { ElMessage.error(e.msg || '上传失败') } finally { loading.value = false } }