之前看过有人用beforeUpload 上传文件,用action不行,因为项目是前后端分离的,无法携带token,我研究了下一最终调试通了。
<el-upload drag multiple
name="multipartfiles" //后台接收文件流的参数名
ref="upload"
:limit="limit" //限制文件数量
:action="imageAction" //上传图片的访问的服务器路径
:data="uploadData" //需要携带的其他参数
:on-preview="handlePreview" //点击时触发的事件
:on-remove="handleRemove" //点击移除文件时触发的事件
:file-list="fileList" //已上传的文件list
:beforeUpload="beforeAVatarUpload" //上传之前触发的事件,我在这里做了上传文件的类型控制
:on-exceed = "onExceed" //和limit一起用 当文件数量超出限制时触发
:onError="uploadError" //上传失败时触发
:onSuccess="uploadSuccess" //上传成功时触发
:auto-upload="true"> //是否自动上传
<i class="el-icon-upload"></i>
<div class="el-upload__text">将图片拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传'jpg/png/jpeg/gif'</div>
</el-upload>
export default {
data () {
return {
imageAction: this.$http.adornUrl(`/file/file/save?token=${this.$cookie.get('token')}`),//。。。我才刚知道token可以不放在header中,直接放在路径后面也行
limit: 1,
fileList: [],
}
},
method: {
// 当设置了取消自动上传的时候,调用此方法开始上传
// submitUpload () {
// this.$refs.upload.submit()
// },
handleRemove (file, fileList) {
if (file.status === 'success') {
this.$http({
url: this.$http.adornUrl('/file/file/delete'),
method: 'post',
data: this.$http.adornData([file.uid], false)
}).then(({data}) => {
this.$message.success('删除图片成功!')
})
}
},
handlePreview (file) {
if (file.status === 'success') {
this.imageVisiable = true
this.$nextTick(() => {
this.$refs.showImage.init(file.url)
})
}
},
onExceed (files, fileList) {
this.$message.error('提示:只能上传一张图片!')
},
// 图片上传
beforeAVatarUpload (file) {
if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
this.$message.error('只支持jpg、png、gif格式的图片!')
return false
}
},
uploadSuccess (response, file, fileList) {
this.fileIds = response.fileIds
console.log('上传图片成功')
},
uploadError (response, file, fileList) {
this.$message.error('上传图片失败!')
},
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestParam("multipartfiles") MultipartFile[] multipartfiles,String productId) throws IOException {
//获取项目编译之后的文件路径,一般是“项目路径/target/classes”
String Path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")+"static/swagger/")).replaceAll("file:/", "").replaceAll("%20", " ").trim();
if(Path.indexOf(":") != 1){
Path = File.separator + Path;
}
//遍历文件
if(multipartfiles != null && multipartfiles.length>0){
for(MultipartFile item : multipartfiles){
String fileName = item.getOriginalFilename();//获取文件名
String filePath = Path + "uploadFiles/uploadFiles";//自定义上传路径
File file = new File(filePath,fileName);
if(!file.exists()){//判断文件夹是否存在,如果不存在则创建
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
file.createNewFile();
}
item.transferTo(file);//上传文件
}
}
return R.ok();
}