Vue.js前端对接Laravel8后端如何实现文件与字符串数据同步上传
问题根源
File是浏览器内置的特殊对象,不支持JSON.stringify()直接序列化,你把携带File对象的sections数组转JSON时,文件字段会被自动处理为空值,这是JS的默认特性,不属于代码语法错误。
解决步骤
前端修改逻辑
需要把文件和普通文本参数拆分处理:
- 生成FormData时,先遍历所有sections中的子章节,把文件单独抽离添加到FormData中,同时给需要序列化的sections对应位置存储文件的唯一标识
- 不要手动指定axios的
Content-Type: multipart/form-data,浏览器会自动补全带分隔符的请求头,手动填写反而会导致文件上传失败
修改后的createCourse方法代码参考:
const createCourse = (e) => { e.preventDefault(); if (v$.value.$invalid) { v$.value.$touch(); return; } const formData = new FormData(); formData.append("course", course.title); formData.append("description", course.description); formData.append("user_id", `${authUser.user.id}`); formData.append("hub_id", `${authUser.hub.id}`); // 遍历sections抽离文件 const serializedSections = JSON.parse(JSON.stringify(sections)) sections.forEach((section, sectionIdx) => { section.sub_sections.forEach((subSection, subIdx) => { if (subSection.file) { // 生成唯一文件标识 const fileKey = `file_${sectionIdx}_${subIdx}` // 把文件实体添加到FormData formData.append(fileKey, subSection.file) // 序列化的结构里存储文件标识,后端用来对应匹配文件 serializedSections[sectionIdx].sub_sections[subIdx].file = fileKey } }) }) // 把处理好的sections序列化后添加到FormData formData.append("sections", JSON.stringify(serializedSections)) showLoader(true); axios.post('http://127.0.0.1:8000/api/v1/courses', formData, { headers: { 'accept': 'application/json', 'Accept-Language': 'en-US,en;q=0.8', } }).then(response => { NotificationService.success(response.data.message); showLoader(false); }).catch(err => { NotificationService.error(err.response); showLoader(false); }); }
后端Laravel处理逻辑
拿到请求后按如下方式匹配获取对应文件即可:
// 先解析拿到sections数组 $sections = json_decode($request->input('sections'), true); foreach ($sections as $sectionIdx => $section) { foreach ($section['sub_sections'] as $subIdx => $subSection) { // 如果存在文件标识,直接获取对应上传的文件实体 if (!empty($subSection['file'])) { $uploadedFile = $request->file($subSection['file']); // 此处写你的文件存储逻辑,比如存到本地存储、云存储,拿到路径后存入数据库即可 // $savePath = $uploadedFile->store('course_attachments'); } // 其他字段的业务处理逻辑 } }
内容的提问来源于stack exchange,提问作者etranz
相关产品推荐
相关产品推荐

