vue+springboot+element上传表单数据和图片同时上传

vue+springboot+element上传表单数据和图片同时上传

参考文章: https://www.cnblogs.com/heikedeblack/p/14280885.html

前端代码:

<template>
	<el-form>
		<el-upload class="upload-demo" action="#" :auto-upload="false" :on-preview="handlePreview"
			:on-remove="handleRemove" :file-list="fileList" :on-change="onchange" list-type="picture">
			<el-button size="small" type="primary">点击上传</el-button>
			<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
		</el-upload>
		<!-- 不能放在el-upload组件里面,否则会弹出选择框,与点击上传的效果一样 -->
		<el-button @click="onsumit" size="small" type="primary">上传</el-button>
	</el-form>
</template>
<script>
	import axios from 'axios'
	export default {
		data() {
			return {
				//用来绑定加入的图片,后续用大图片
				dialogImageUrl: '',
				dialogVisible: false,
				//用来接收缓存中的图片
				fileList: []
			};
		},
		methods: {
			handleRemove(file, fileList) { //文件列表移除文件时的钩子
				console.log(file, fileList);
				console.log(file.raw)
			},
			handlePreview(file) { //点击文件列表中已上传的文件时的钩子
				// console.log(file);
			},
			onchange(file, fileList) {
				// console.log("上传时的动作")
				// console.log(file, fileList);
				// console.log(file.raw)
				// fileList.push('file', file.raw);
				this.fileList = fileList;//每一个改变都会将el-upload里面的图片传递的参数复制到this.filelist去
			},
			onsumit() { //上传
				let formData = new FormData();
				for (let i = 0; i < this.fileList.length; i++) {
					//this.fileList[i].raw:获取图片格式
					//这里的file必须和后端Controller中的requestparam参数一致,才能上传成功,否则会报400错误
					formData.append("file", this.fileList[i].raw, this.fileList[i].name);
				}
				formData.append('uploadrole', "lizy");
				console.log(formData)
				//这里重新创建了一个axios实例,是因为我在全局配置里的Content-type是appliacation/json,而这里我想要使用multipart/form-data
				const http1 = axios.create({
					headers: {
						// 'Content-Type': 'multipart/form-data'
						"Content-Type": "multipart/form-data"
					}
				})
				http1({
						url: 'http://localhost:8080/uploadMenucolumn',
						method: 'post',
						data: formData
					})
					.then((res) => {
						console.log(res.data);
					})
					.catch((err) => {
						console.log(err);
					});
			}
		}
	}
</script>

<style>
</style>

后端代码

@RequestMapping("/uploadMenucolumn")
	@ResponseBody
	public Result uploadMenucolumn(@RequestParam("file") MultipartFile[] files,
										   //表单参数,需要加入所有的参数,为补全
										   @RequestParam("uploadrole") String uploadrole
	) throws IOException {
		for (MultipartFile file : files) {
			System.out.println("文件名 = " + file.getOriginalFilename());
			System.out.println("文件类型= " + file.getContentType());
			// 保存到硬盘
			//保存到硬盘
			//路径示例 1) Windows c:/, 3) Mac ~/Documents/
			String filePath = "D:/uploadfiles/";
			if (!new File(filePath).exists()) {
				new File(filePath).mkdirs();
			}
			//复制图片到该路径下
			file.transferTo(new File(filePath + file.getOriginalFilename()));
		}
		//图片附带的参数
		System.out.println("uploadrole=" + uploadrole);
		//return new Result(ResultCode.SUCCESS);自定义返回类型
		return new Result(ResultCode.SUCCESS);

	}

后台效果

文件名 = QQ截图20210430194517.png
文件类型= image/png
QQ截图20210430194517.png image/png
2021-05-18 10:48:43.359 DEBUG 1848 --- [nio-8080-exec-2] c.e.h.controller.FileUploadController    : 文件名 = QQ截图20210426234023.png
2021-05-18 10:48:43.359 DEBUG 1848 --- [nio-8080-exec-2] c.e.h.controller.FileUploadController    : 文件类型= image/png
文件名 = QQ截图20210426234023.png
文件类型= image/png
QQ截图20210426234023.png image/png
2021-05-18 10:48:43.361 DEBUG 1848 --- [nio-8080-exec-2] c.e.h.controller.FileUploadController    : 文件名 = QQ截图20210502000858.png
2021-05-18 10:48:43.361 DEBUG 1848 --- [nio-8080-exec-2] c.e.h.controller.FileUploadController    : 文件类型= image/png
文件名 = QQ截图20210502000858.png
文件类型= image/png
QQ截图20210502000858.png image/png
uploadrole=lizy
  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在端,可以使用 Element UI 的 Upload 组件来上文件,同时将数据也一并提交到后端。具体代码如下: ```html <template> <el-form :model="form" label-width="120px"> <el-form-item label="姓名"> <el-input v-model="form.name"></el-input> </el-form-item> <el-form-item label="头像"> <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> </el-form-item> </el-form> </template> <script> export default { data() { return { form: { name: '', avatar: '' }, imageUrl: '' } }, methods: { handleAvatarSuccess(res, file) { this.form.avatar = res.url this.imageUrl = URL.createObjectURL(file.raw) }, beforeAvatarUpload(file) { // 限制上图片的大小和格式 const isJPG = file.type === 'image/jpeg' const isPNG = file.type === 'image/png' const isLt2M = file.size / 1024 / 1024 < 2 if (!isJPG && !isPNG) { this.$message.error('上头像图片只能是 JPG/PNG 格式!') return false } if (!isLt2M) { this.$message.error('上头像图片大小不能超过 2MB!') return false } return true }, submitForm() { this.$refs.form.validate(valid => { if (valid) { const formData = new FormData() formData.append('name', this.form.name) formData.append('avatar', this.form.avatar) // 将数据和文件一起提交到后端 this.$http.post('/api/user', formData).then(res => { this.$message.success('提交成功') }).catch(error => { this.$message.error('提交失败') }) } else { this.$message.error('验证失败') return false } }) } } } </script> ``` 在后端,使用 Spring Boot 的 MultipartFile 类型来接收上的文件,并在 Controller 中处理数据和文件上的逻辑。具体代码如下: ```java @RestController @RequestMapping("/api") public class UserController { @PostMapping("/user") public ResponseEntity<?> createUser(@RequestParam("name") String name, @RequestParam("avatar") MultipartFile avatar) { // 处理数据和文件上的逻辑 // ... return ResponseEntity.ok().body("创建用户成功"); } } ``` 需要注意的是,由于使用了 FormData 对象来提交数据和文件,因此需要在前端使用 axios 或者其他 HTTP 请求库来发送 POST 请求。在上面的代码中,我使用了 Vue.js 的官方插件 vue-resource 来发送 POST 请求。如果您使用的是 axios,则可以将代码修改为: ```javascript import axios from 'axios' submitForm() { this.$refs.form.validate(valid => { if (valid) { const formData = new FormData() formData.append('name', this.form.name) formData.append('avatar', this.form.avatar) // 将数据和文件一起提交到后端 axios.post('/api/user', formData).then(res => { this.$message.success('提交成功') }).catch(error => { this.$message.error('提交失败') }) } else { this.$message.error('验证失败') return false } }) } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值