elm ui , elm upload 上传图片,java springboot post
<el-upload
action="' '"
list-type="picture-card"
:limit="3"
show-file-list
:auto-upload="false"
:on-change="change"
multiple
>
<i class="el-icon-plus" />
</el-upload>
<div class="submitFeedbackBtn" @click="submit">提交</div>
js
methods: {
submit() {
const config = {
timeout: 30000,
headers: {
'Content-Type': 'multipart/form-data' // 设置headers
}
}
const formData = new FormData()
// post formData 后端接收
// https://blog.csdn.net/weixin_44294593/article/details/103070687
var that = this
// 一定是file 吗
// 首先判断是否上传了图片,如果上传了图片,将图片存入到formData中
console.log(this.dataList)
if (this.dataList) {
// that.dataList.forEach((item, index) => {
// // console.log(item)
// // 这里的名字就是 formdata 的
// formData.append(index, item)
// })
// 注意这里的 file 名字就是 后端接收要用的 @RequestParam("file") MultipartFile picture,
formData.append('file', that.dataList[0])
}
// method.post()
// console.log(formData.get(0));
axios.post(
axiosUrl + 'present/img', // 请求后端的url
formData,
config
)
.then((res) => {
console.log(res)
if (res.data.status === 'ok') {
// 上传成功
console.log('上传成功')
this.$router.push({
path: './'
})
} else {
alert('上传失败')
}
})
.catch((error) => {
console.log('请求失败')
})
// 用户可以在上传完成之后将数组给清空,这里直接跳转到首页了,没有做清空的操作
},
change(file, fileList) {
// 将每次图片数组变化的时候,实时的进行监听,更改数组里面的图片数据
var arr = []
fileList.forEach((item) => {
arr.push(item.raw)
})
this.dataList = arr
console.log(arr)
},
java
@ApiOperation(value = "上传图片",notes="把图片存储在服务器指定位置")
@RequestMapping(value="/img",method= RequestMethod.POST)
// public JSONObject upload(@RequestParam MultipartFile picture, HttpServletRequest request) {
public JSONObject upload(@RequestParam("file") MultipartFile picture, HttpServletRequest request) {
log.info("picture {}",picture);
JSONObject result=new JSONObject();
//获取文件在服务器的储存位置
String path = "D:\\pic";
File filePath = new File(path);
log.info("filePath {}",filePath);
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdir();
}
//获取原始文件名称(包含格式)
String originalFileName = picture.getOriginalFilename();
//获取文件类型,以最后一个`.`为标识
String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
//获取文件名称(不包含格式)
String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
String fileName = System.currentTimeMillis() + " " +name + "." + type;
log.info("fileName {}",fileName);
//在指定路径下创建一个文件
File targetFile = new File(path, fileName);
//将文件保存到服务器指定位置
try {
picture.transferTo(targetFile);
result.put("port","200");
result.put("url" ,fileName);
//将文件在服务器的存储路径返回
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
前端
vue代码来自