Vue+SpringBoot后端接收包含单属性和List数组的json对象

这次主要是针对springboot后台接收的json中包含多对象(如List数组/单属性)所写的一篇文章。虽然网上类似情况很多,尝试了一个晚上,都没有解决问题,最后还是在师兄的帮助下完美解决。

vue前端代码
SysAddManual.vue

var Params = {
  type: "typeA",
  title: "titleA",
  authors: [{name:"upxuan", age:"18"}, {name:"susen", age:"18"}]
}
console.log(Params)
this.$ajax({
  url: '/api/manualAdd',
  method: 'post',
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: Params
}).then( res => {
  console.log(res)
})

manualAddController.java

@RequestMapping("/manualAdd")
@ResponseBody
public String AddManualJpaper (@RequestBody RequestManualAddData data) {
	System.out.println("User:" + data.getType() + "," + data.getTitle());
	System.out.println("Authors:" + data.getAuthors().get(0).getName() + "," + data.getAuthors().get(0).getAge());
    return "Get it";
}

接收的数据对象类
RequestManualAddData .java

private String type;
private String title;
private List<AuthorsModel> authors;

public String getType() {
	return type;
}

public void setType(String type) {
	this.type = type;
}

public String getTitle() {
	return title;
}

public void setTitle(String title) {
	this.title = title;
}
public List<AuthorsModel> getAuthors() {
	return authors;
}

public void setAuthors(List<AuthorsModel> authors) {
	this.authors = authors;
}

作者对象类
AuthorsModel.java

private String name;
private int age;
public String getName() {
	return name;
}

public void setName(String name) {
	this.name = name;
}
public int getAge() {
	return age;
}

public void setAge(int age) {
	this.age = age;
}

后端打印出前端发送的数据,最后前端返回的结果如图: Alt
如果解决了你的问题,顺手点个赞呗(╹▽╹)

### Vue3 中实现多文件上传并传递至 SpringBoot 后端的方式 #### 前端部分 (Vue3) 在 Vue3 中可以借助 Element Plus 的 `<el-upload>` 组件来实现多文件上传功能。通过配置 `multiple` 属性允许用户选择多个文件,并将这些文件存储在一个数组中以便后续提交。 以下是完整的前端代码示: ```html <template> <el-upload ref="uploadRef" action="" multiple :auto-upload="false" :on-change="handleChange" :before-upload="handleBeforeUpload" :file-list="fileList"> <el-button type="primary">点击上传</el-button> <template #tip> <div class="el-upload__tip">仅支持jpg/png格式,大小不超过500KB。</div> </template> </el-upload> <el-button @click="submitFiles" style="margin-top: 20px;">提交</el-button> </template> <script setup> import { ref } from 'vue'; import axios from 'axios'; const fileList = ref([]); const uploadRef = ref(null); // 文件改变事件回调函数 function handleChange(file, fileListParam) { console.log('Selected file:', file); } // 提交前校验文件 function handleBeforeUpload(file) { const isJPGorPNG = ['image/jpeg', 'image/png'].includes(file.type); const isLt500K = file.size / 1024 < 500; if (!isJPGorPNG) { alert('仅支持 JPG/PNG 格式的图片!'); return false; } if (!isLt500K) { alert('个文件大小不得超过 500 KB!'); return false; } return true; } // 提交文件到后端 async function submitFiles() { const formData = new FormData(); // 遍历文件列表并将它们加入FormData对象 fileList.value.forEach((fileItem) => { formData.append('files', fileItem.raw); // 将文件附加到表数据中[^2] }); try { await axios.post('/api/upload/multiple-files', formData, { headers: { 'Content-Type': 'multipart/form-data' }, }); alert('文件上传成功!'); uploadRef.value.clearFiles(); // 清除已上传的文件列表 } catch (error) { console.error(error); alert('文件上传失败,请重试!'); } } </script> ``` --- #### 后端部分 (Spring Boot) 在 Spring Boot 中可以通过 `@RequestParam` 注解接收来自前端的多文件数据。为了兼容复杂的 JSON 数据结构其他参数,推荐使用 `@RequestPart` 来解析请求体中的不同部分。 以下是后端代码示: ```java import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.List; @RestController @RequestMapping("/api/upload") public class FileUploadController { @PostMapping("/multiple-files") public String handleFileUpload(@RequestPart("files") List<MultipartFile> files) throws Exception { StringBuilder resultMessage = new StringBuilder(); for (MultipartFile file : files) { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // 存储文件逻辑(此处省略) resultMessage.append(String.format("文件 %s 已保存。\n", file.getOriginalFilename())); } } return resultMessage.toString(); } } ``` 上述代码片段展示了如何利用 `@RequestPart` 接收名为 `"files"` 的字段,并将其转换为 `List<MultipartFile>` 类型以处理多个文件[^1]。 --- #### 注意事项 1. **跨域问题**: 如果前后端分离部署,则需确保 Spring Boot 开启 CORS 支持。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*"); } } ``` 2. **文件大小限制**: 可以在 `application.properties` 或 `application.yml` 中调整最大上传文件大小。 ```properties spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` 3. **安全性**: 对于生产环境,建议增加更严格的验证机制以及防止恶意攻击的安全措施。 --- ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值