axios封装和文件上传

本文详细介绍了如何在Vue项目中使用axios进行HTTP请求,包括封装axios、对象和JSON字符串之间的转换、设置拦截器以及在Vue3中处理GET请求。同时涵盖了前端向SpringBoot后端上传文件的方法和后端文件接收处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考资料

axios发送四种方式

对象和json字符串之间转换 (qs)

后端接受文件(一般格式)

SpringBoot+Vue前后端文件传输问题总结


一,axios封装

事前准备

禁止eslint检查
在vue.config.js中 添加 lintOnSave: false
如下图所示

在这里插入图片描述

如果没有安装axios:

npm install axios

使用json-server

使用json-server以测试获取后端的数据

  1. 安装:

npm install -g json-server

  1. 创建db.json
{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}
  1. 启动json-server

json-server –watch db.json
json-server –watch db.json -d 2000 #延时两秒在返回结果



编写 plugins/axios

使用拦截器: 拦截器在vue2 vue3中都可以使用

使用拦截器这样写

import axios from "axios";

// Add a request interceptor
axios.interceptors.request.use(
    function (config) {
        // Do something before request is sent
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

// Add a response interceptor
axios.interceptors.response.use(
    function (response) {
        console.log("响应", response);
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        return response;
    },
    function (error) {
        // Any status code that false outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
    }
);


在main.js中只需添加一行
import "./plugins/axios1"

在组件中使用axios
// 1) 使用axios({ })
axios({
	url: "http://localhost:3000/posts",
  data: "",
  methods: "GET",
}).then((res)=>{
	console.log(res);
})

// 2) 使用axios.xxx()
axios.get("/api/depts").then((res)=>{
	console.log(res)
});

在vue3中使用 myRequest

import qs from "qs";
import axios from "axios";

const myRequest = (options) => {
  return new Promise((resolve, reject) => {
    let url = options.url;
    let method = options.method || "GET";
    let data = options.data || {};
    if (method === "GET") {
      // 将data对象转化成字符串
      data = qs.stringify(data);
    }
    axios({
      method,
      url,
      data,
    })
      .then((res) => {
        console.log("响应 res.data = ")
        console.log(res.data)
        // 请求错误 res.data为空,或者res.data.status为空
        if (!(res.data && res.data.status)) {
          resolve(res);
        } else {
          // 其他情况 正确情况下
          resolve(res);
        }
      })
      .catch(() => {
        resolve({
          data: {
            msg: "请求错误",
            status: -1,
          },
        });
      });
  });
};
export default myRequest;

在main.js 中使用 globalProperties.$myRequest

import App from './App.vue'
import { createApp } from 'vue'
import myRequest from "./plugins/axios";
const app = createApp(App)
app.config.globalProperties.$myRequest = myRequest; 

在组件中使用

this.$myRequest({
  url: "http://localhost:3000/posts",
  data: {},
  methods: "GET",
}).then((res) => {
  console.log(res.data)
})

在vue2中使用 _axios

在使用 axios

import axios from 'axios';

let _axios=axios.create({
  // 这里写入配置
  baseURL: 'http://localhost:8080/', // 设置所有 Axios 请求的基本 URL
  timeout: 10*1000 // 设置最长时间,单位毫秒
})
export default _axios

在main.js中 引入

import Vue from 'vue'
import App from './App.vue'
import _axios from './plugin/axios'

Vue.prototype.$axios=_axios //给全局Vue实例对象添加axios属性

在组件中使用

this.$axios.get('http://localhost:3000/posts').then(function (resp) {
  console.log(resp.data)
})




二,在vue中向后端传递文件

前端信息

页面信息:

<div>
  <input type="file" name="" ref="file">
  <button @click="click">上传</button>
</div>

后台信息:

methods: {
  click(){
    // 数据这里我使用了 new FormData
    var forms = new FormData()
    var configs = { // 上传文件 请求头要设置成下面这样
      headers:{'Content-Type':'multipart/form-data'}
    };
    forms.append('file',this.$refs.file.files[0]);// 获取上传图片信息
    //forms.append('type','img'); // 添加一些图片的自定义信息
    //forms.append('name','touxiang.jpg');
    axios.post('/api/upload',forms ,configs).then(res=>{
      console.log("res = ")
      console.log(res.data.data)
    })
  }
},

后端信息:

common

返回信息

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
    private Integer code;
    private String msg;
    private T data;

    private static final Integer code_ok = 1;
    private static final String msg_success = "操作成功";
    private static final String msg_error = "操作失败";


    // 增删改 成功
    public static <T> Result<T> success(){
        return new Result<>(1,"success",null);
    }

    // 查询 成功
    public static <T> Result<T> success(Integer code,T data){
        return new Result<>(code,"success",data);
    }

    // 四项全部失败
    public static <T> Result<T> error(Integer code,String msg,T data){
        return new Result<>(code,msg,data);
    }
}

controller

通过时间定义文件名:

Date date = new Date();
long t = date.getTime();

// 创建日期格式化对象,在获取格式化对象时可以指定风格
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); //时间格式
String str = df.format(date);  // 获得从 1977 某个时间的到此的毫秒数

后端接受文件

@Slf4j
@RestController
public class UploadController {

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error(0, "文件是空的", null);
        }

        log.info("文件上传 {}", file);

        try {
            // 获得文件原始名称
            String originalFilename = file.getOriginalFilename();
            System.out.println("originalFilename = " + originalFilename);
	
        	// 设置日期
            Date date = new Date();
            // 获得毫秒数
            long t = date.getTime();

            // 创建日期格式化对象,在获取格式化对象时可以指定风格
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String str = df.format(date);
            str += Long.toString(t);
            str += "-";
            str += originalFilename;
            System.out.println(str);

        	// 将文件储存在这个位置,并重新命名
            file.transferTo(new File("C:\\Users\\yang99977\\Pictures\\Saved Pictures\\img\\" + str));

            return Result.success();
        } catch (Exception e) {
            log.info("出错了");
            return Result.error(0, "文件上传失败", null);
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值