ElementUI上传图片400错误解决
问题描述:图片上传功能包括三个字段,1.图片名称,2.图片是否显示状态,3.上传的图片本身
方法一.使用before-upload完成上传操作
<el-upload ref="upload" action="012" :before-upload="beforeBannerUpload" n-change="imgChange" :auto-upload="false" name="file" accept="image/gif, image/jpeg, image/png" :show-file-list="false">
<div class="bannerPic">轮播图片:</div>
<el-button slot="trigger">选择上传图片</el-button>
<div ref="fileList" class="fileList" v-if="file.name">{{file.name}}</div>
<div class="fail-upload_tip" v-if="this.tipMessage">{{tipMessage}}</div>
<div class="tip-message">备注:图片只能上传.png/.jpg/.gif格式,图片不能超过1M。</div>
<div class="bannerAddOps">
<el-button type="primary" @click="uploadImg">提交</el-button>
<el-button type="primary" @click="cancel">返回</el-button>
</div>
</el-upload>
beforeBannerUpload(file){
let param = new FormData();
param.append('file', file);
param.append('title',this.bannerData.title);
param.append('showState',this.bannerData.showState);
this.bannerUpload(param);
},
async bannerUpload(param){
try{
await this.bannerUploadAction();
}catch(err){
this.$refs.upload.clearFiles();
this.tipMessage = "上传图片失败";
}
},
bannerUploadAction(){
const url = '/plug-operation-mgmt/banner/add';
const config = { reqInterceptors: true, resInterceptors: true };
this.$axiosPost(url,param,config).then((res)=>{
this.$refs.upload.clearFiles();
});
}
存在的问题是:默认的action还是会触发,会出现400错误,但不影响功能。
方法二:ElementUI上传控件有默认的参数可以试用
<el-upload ref="upload" action="http://localhost:8080/plug-operation-mgmt/banner/add" n-change="imgChange" :auto-upload="false" name="file" :data="bannerData" accept="image/gif, image/jpeg, image/png" :show-file-list="false">
<div class="bannerPic">轮播图片:</div>
<el-button slot="trigger">选择上传图片</el-button>
<div ref="fileList" class="fileList" v-if="file.name">{{file.name}}</div>
<div class="fail-upload_tip" v-if="this.tipMessage">{{tipMessage}}</div>
<div class="tip-message">备注:图片只能上传.png/.jpg/.gif格式,图片不能超过1M。</div>
<div class="bannerAddOps">
<el-button type="primary" @click="uploadImg">提交</el-button>
<el-button type="primary" @click="cancel">返回</el-button>
</div>
</el-upload>
其中bannerData中就是额外的参数图片名称和显示状态,直接触发默认action就可以了。其中name="file"中file为服务端接口中指定文件的名称