vue传参

一、非文件上传:

@RequseParam与@RequestBody接收参数,前端传参,params传给@RequseParam,data传给@RequestBody

1、后端:现有两个接口,

package com.demo.rest;

import com.demo.dto.ResponseMessage;
import com.demo.dto.UserDTO;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/test")
public class Test {

    @RequestMapping("/paramTest")
    public ResponseMessage param(UserDTO user){
        System.out.println("param"+user.getUserName());
        return ResponseMessage.success();
    }

    @RequestMapping("/bodyTest")
    public ResponseMessage body(@RequestBody List<String> ids){
        System.out.println(ids);
        return ResponseMessage.success();
    }
}

 

2、前端封装的request请求util:

import axios from 'axios'
// 配置session跨域
axios.defaults.withCredentials = true
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['token'] = store.getters.token // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  //文件上传
  if (config.method === 'post') {
    if (config.upload) { // 上传图片则添加headers
      config.headers['Content-Type'] = 'multipart/form-data'
      config.timeout = 360000
    } 
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
  /**
  * code为非20000是抛错 可结合自己业务进行修改
  */
    const res = response.data
    // 下载请求
    //if (res instanceof Blob) {
      //return res
    //}

    if (res.code !== 200 && res.code !=300) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })

      // 401 token失效
      if (res.code === 401) {
        // MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
        //   confirmButtonText: '重新登录',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   store.dispatch('FedLogOut').then(() => {
        //     location.reload()// 为了重新实例化vue-router对象 避免bug
        //   })
        // })
     
        store.dispatch('FedLogOut').then(() => {
          location.reload()// 为了重新实例化vue-router对象 避免bug
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

3、前端api:

import request from '@/utils/request'



export function paramTest(user){
  let userName = user.userName
  let userNickName = user.userNickName
  return request({
    url: '/test/paramTest',
    method: 'post',
    params: { userName,userNickName }
  })
}

export function bodyTest(ids) {
  return request({
    url: '/test/bodyTest',
    method: 'post',
    data: ids
  })
}

4、页面js:

 <script>
  import { getAllUsers } from '@/api/user'
   import { paramTest,bodyTest } from '@/api/test'
    export default {
      data() {
        return {
         userList:[]
        }
      },

       created(){
        this.getAllUserList();
        this.getParam();
        this.getBody();
      },

      methods:{
        
        getParam(){
          let user = {'userName':'我是name','userNickName':'我是nockName'}
              paramTest( user).then(res=>{
                 
               }) 
          }  ,
          getBody(){
            let ids = ['1','a','b'];
              bodyTest( ids).then(res=>{
                  
                })
          }  ,
          getAllUserList(){
              getAllUsers().then(res=>{
                  this.userList = res.data
               }).catch(err => {
                    console.log(err)
                }) 
          }  
      }
    }

   
  </script>

后端打印的请求信息如下:

[1, a, b]
param我是name

二、文件上传:

1、前端api

import request from '@/utils/request'

export function upload(formDatas) {
  return request({
    url: '/file/upload',
    method: 'post',
    upload: true,
    data: formDatas
  })
}

export function download() {
  return request({
    url: '/file/download',
    method: 'post'
  })
}

2、前端页面: 

<template>
  <div>
    <div>
      <!-- <a href="javacript:void(0)" @click="exportTemplate">下载模板</a> -->
      <el-button @click="exportTemplate">下载</el-button>
    </div>
    <div class="upload_btn">
      <span>上传图片</span>
      <input
        type="file"
        multiple
        accept="image/gif, image/jpeg, image/png, image/jpg"
        @change="uploadImg($event)"
      />
      <!-- <el-upload
        class="upload-demo"
        drag
        multiple
        on-change="uploadImg($event)"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处,或
          <em>点击上传</em>
        </div>
       
      </el-upload> -->
    </div>
  </div>
</template>

<script>
import { upload, download } from "@/api/upload";
export default {
  methods: {
    uploadImg(ev) {
      var files = ev.target.files;
      let formData = new FormData();

      if (!files || files.length === 0) return;
      for (var i = 0; i < files.length; i++) {
        formData.append("files", files[i]);
      }

      upload(formData)
        .then(res => {
          alert("上传成功");
        })
        .catch(() => {});
    },
    exportTemplate() {
      debugger;
      let baseURL = process.env.BASE_API;
      let url = baseURL + "file/download";
      alert(url);
      window.location.href = url;
    },
    exportTemplate1() {
      //download().then(res => {});
      download()
        .then(res => {
          //     debugger;
          //   if (!res) {
          //     return;
          //   }
          //   const url = window.URL.createObjectURL(new Blob([res]));
          //   const link = document.createElement("a");
          //   link.style.display = "none";
          //   link.href = url;
          //   link.setAttribute("download", "user.xlsx");
          //   document.body.appendChild(link);
          //   link.click();
        })
        .catch(err => {
          // this.$message.error(err);
        });
    }
  }
};
</script>

3、后端接口:

   @RequestMapping("/upload")
    public ResponseMessage uploadFile(@RequestBody MultipartFile[] files) throws IOException {
        JWTUserDTO jwtUser = (JWTUserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        for (MultipartFile file : files) {
            long size = file.getSize();
            String fileName = file.getOriginalFilename();
            System.out.println(fileName + " " + size);
        }
        return ResponseMessage.success("上传成功");
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_t_y_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值