https://blog.csdn.net/gaopinqiang/article/details/107328936
前端JS代碼:
apply(){ let data = new FormData(); // todo 非常重要,一定要加file.raw,從瀏覽器中查看需要使用binary類型,后台才能正確接收 this.form.files = this.fileList[0].raw console.log(this.fileList[0].raw) // 將form表單中的值都賦值給FormData傳遞給后台 for(let key in this.form){ console.log(this.form[key]) data.append(key,this.form[key]) } this.$axios .post('/user/apply',data,{ headers: { 'Content-Type': 'multipart/form-data' }})// 第一種,直就傳個json數據,不需要設置headers // .post('/user/apply',this.form)// 第三種,可以直接傳遞這個form(推薦) .then(resp => { console.log('請求本地接口OK') console.log(resp) if(resp.data.code == -1){ // 接口返回-1,就是注冊失敗,提示消息提示用戶 this.$message({ message: resp.data.msg, type: 'error' }); } else if(resp.data.code == 0){ console.log(resp.data) //注冊成功 this.$message({ message: "報名成功", type: 'success' }); // 跳轉到登錄頁面 // this.$router.push('/login') } }) .catch(function (error) { // 請求失敗處理 console.log('請求本地接口失敗' + error); }); },
Java代碼:
@Transactional @ApiOperation(notes = "報名參加接口", value = "報名參加接口", httpMethod = "POST") @PostMapping(value = "/apply",produces = "application/json;charset=UTF-8") public Result apply(RegistrationInfo registrationInfo, @RequestParam(value = "files")MultipartFile files){ //同時接收RegistrationInfo這個bean參數和參數名為files的MultipartFile類型參數。 //我們使用DataForm,格式提交就可以。 ... }