vue传参

向右看齐 2023-02-26 05:27 98阅读 0赞

一、非文件上传:

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

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

  1. package com.demo.rest;
  2. import com.demo.dto.ResponseMessage;
  3. import com.demo.dto.UserDTO;
  4. import org.springframework.web.bind.annotation.RequestBody;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestParam;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import java.util.List;
  10. @RestController
  11. @RequestMapping("/test")
  12. public class Test {
  13. @RequestMapping("/paramTest")
  14. public ResponseMessage param(UserDTO user){
  15. System.out.println("param"+user.getUserName());
  16. return ResponseMessage.success();
  17. }
  18. @RequestMapping("/bodyTest")
  19. public ResponseMessage body(@RequestBody List<String> ids){
  20. System.out.println(ids);
  21. return ResponseMessage.success();
  22. }
  23. }

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

  1. import axios from 'axios'
  2. // 配置session跨域
  3. axios.defaults.withCredentials = true
  4. import { Message, MessageBox } from 'element-ui'
  5. import store from '../store'
  6. import { getToken } from '@/utils/auth'
  7. // 创建axios实例
  8. const service = axios.create({
  9. baseURL: process.env.BASE_API, // api的base_url
  10. timeout: 5000 // 请求超时时间
  11. })
  12. // request拦截器
  13. service.interceptors.request.use(config => {
  14. if (store.getters.token) {
  15. config.headers['token'] = store.getters.token // 让每个请求携带自定义token 请根据实际情况自行修改
  16. }
  17. //文件上传
  18. if (config.method === 'post') {
  19. if (config.upload) { // 上传图片则添加headers
  20. config.headers['Content-Type'] = 'multipart/form-data'
  21. config.timeout = 360000
  22. }
  23. }
  24. return config
  25. }, error => {
  26. // Do something with request error
  27. console.log(error) // for debug
  28. Promise.reject(error)
  29. })
  30. // respone拦截器
  31. service.interceptors.response.use(
  32. response => {
  33. /**
  34. * code为非20000是抛错 可结合自己业务进行修改
  35. */
  36. const res = response.data
  37. // 下载请求
  38. //if (res instanceof Blob) {
  39. //return res
  40. //}
  41. if (res.code !== 200 && res.code !=300) {
  42. Message({
  43. message: res.message,
  44. type: 'error',
  45. duration: 5 * 1000
  46. })
  47. // 401 token失效
  48. if (res.code === 401) {
  49. // MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
  50. // confirmButtonText: '重新登录',
  51. // cancelButtonText: '取消',
  52. // type: 'warning'
  53. // }).then(() => {
  54. // store.dispatch('FedLogOut').then(() => {
  55. // location.reload()// 为了重新实例化vue-router对象 避免bug
  56. // })
  57. // })
  58. store.dispatch('FedLogOut').then(() => {
  59. location.reload()// 为了重新实例化vue-router对象 避免bug
  60. })
  61. }
  62. return Promise.reject('error')
  63. } else {
  64. return response.data
  65. }
  66. },
  67. error => {
  68. console.log('err' + error)// for debug
  69. Message({
  70. message: error.message,
  71. type: 'error',
  72. duration: 5 * 1000
  73. })
  74. return Promise.reject(error)
  75. }
  76. )
  77. export default service

3、前端api:

  1. import request from '@/utils/request'
  2. export function paramTest(user){
  3. let userName = user.userName
  4. let userNickName = user.userNickName
  5. return request({
  6. url: '/test/paramTest',
  7. method: 'post',
  8. params: { userName,userNickName }
  9. })
  10. }
  11. export function bodyTest(ids) {
  12. return request({
  13. url: '/test/bodyTest',
  14. method: 'post',
  15. data: ids
  16. })
  17. }

4、页面js:

  1. <script>
  2. import { getAllUsers } from '@/api/user'
  3. import { paramTest,bodyTest } from '@/api/test'
  4. export default {
  5. data() {
  6. return {
  7. userList:[]
  8. }
  9. },
  10. created(){
  11. this.getAllUserList();
  12. this.getParam();
  13. this.getBody();
  14. },
  15. methods:{
  16. getParam(){
  17. let user = {'userName':'我是name','userNickName':'我是nockName'}
  18. paramTest( user).then(res=>{
  19. })
  20. } ,
  21. getBody(){
  22. let ids = ['1','a','b'];
  23. bodyTest( ids).then(res=>{
  24. })
  25. } ,
  26. getAllUserList(){
  27. getAllUsers().then(res=>{
  28. this.userList = res.data
  29. }).catch(err => {
  30. console.log(err)
  31. })
  32. }
  33. }
  34. }
  35. </script>

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

[1, a, b]
param我是name

二、文件上传:

1、前端api

  1. import request from '@/utils/request'
  2. export function upload(formDatas) {
  3. return request({
  4. url: '/file/upload',
  5. method: 'post',
  6. upload: true,
  7. data: formDatas
  8. })
  9. }
  10. export function download() {
  11. return request({
  12. url: '/file/download',
  13. method: 'post'
  14. })
  15. }

2、前端页面:

  1. <template>
  2. <div>
  3. <div>
  4. <!-- <a href="javacript:void(0)" @click="exportTemplate">下载模板</a> -->
  5. <el-button @click="exportTemplate">下载</el-button>
  6. </div>
  7. <div class="upload_btn">
  8. <span>上传图片</span>
  9. <input
  10. type="file"
  11. multiple
  12. accept="image/gif, image/jpeg, image/png, image/jpg"
  13. @change="uploadImg($event)"
  14. />
  15. <!-- <el-upload
  16. class="upload-demo"
  17. drag
  18. multiple
  19. on-change="uploadImg($event)"
  20. >
  21. <i class="el-icon-upload"></i>
  22. <div class="el-upload__text">
  23. 将文件拖到此处,或
  24. <em>点击上传</em>
  25. </div>
  26. </el-upload> -->
  27. </div>
  28. </div>
  29. </template>
  30. <script>
  31. import { upload, download } from "@/api/upload";
  32. export default {
  33. methods: {
  34. uploadImg(ev) {
  35. var files = ev.target.files;
  36. let formData = new FormData();
  37. if (!files || files.length === 0) return;
  38. for (var i = 0; i < files.length; i++) {
  39. formData.append("files", files[i]);
  40. }
  41. upload(formData)
  42. .then(res => {
  43. alert("上传成功");
  44. })
  45. .catch(() => {});
  46. },
  47. exportTemplate() {
  48. debugger;
  49. let baseURL = process.env.BASE_API;
  50. let url = baseURL + "file/download";
  51. alert(url);
  52. window.location.href = url;
  53. },
  54. exportTemplate1() {
  55. //download().then(res => {});
  56. download()
  57. .then(res => {
  58. // debugger;
  59. // if (!res) {
  60. // return;
  61. // }
  62. // const url = window.URL.createObjectURL(new Blob([res]));
  63. // const link = document.createElement("a");
  64. // link.style.display = "none";
  65. // link.href = url;
  66. // link.setAttribute("download", "user.xlsx");
  67. // document.body.appendChild(link);
  68. // link.click();
  69. })
  70. .catch(err => {
  71. // this.$message.error(err);
  72. });
  73. }
  74. }
  75. };
  76. </script>

3、后端接口:

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

发表评论

表情:
评论列表 (有 0 条评论,98人围观)

还没有评论,来说两句吧...

相关阅读

    相关 vue

    一、非文件上传: @RequseParam与@RequestBody接收参数,前端传参,params传给@RequseParam,data传给@RequestBody 1、

    相关 vue组建

    一、父子组件传参 vm.$emit( event, arg ) //触发当前实例上的事件 【子传父】借助一个中转的父组件自定义函数,在子组件中利用 $emit 触发父组