axios笔记

axios笔记

axios上传文件案例
**********************************上传多个文件**************************************
    <input v-for="arr in array" type="file" ref = "file" >
	<button @click="upload">upload</button>

    data(){
      return {
        array: [1, 2 , 3]
      }
    },

methods: {
      upload(){
        let formData = new FormData()
        let files = this.$refs.file
        for(let i = 0; i < files.length; i++){
          console.debug("files_me")
          formData.append("img", files[i].files[0])
        }
        this.axios.post('/api/upload_img',formData,{
          'Content-Type':'multipart/form-data'
        }).then(res=>{
            console.debug(res)
        }).catch(err=>{
          console.debug(err)
        })
      }
}


    @PostMapping("/upload_img")
    public String upload_img(@RequestParam(value = "img",  required = false) MultipartFile[] files) throws IOException {

        File f1 = new File("i:/1.jpg");
        File f2 = new File("i:/2.jpg");
        File f3 = new File("i:/3.jpg");
        if(files!=null){
            System.out.println(files.length);
            for (MultipartFile f: files){
                System.out.println(f.getOriginalFilename());
            }
        }else{
            System.out.println("files == null");
        }

        files[0].transferTo(f1);
        files[2].transferTo(f3);
        files[1].transferTo(f2);

        return "upload success";
    }

**********************************上传多个文件结束**************************************




**********************************上传单个文件********************************
<template>
    <div class="cancelRequest">
        <div>姓名:<input type="text" v-model="name"></div>
        <div>头像:<input type="file" ref="file"></div>
        <div @click="save">保存</div>
    </div>
</template>
 
<script>
export default {
    data(){
        return {
            value:''
        }
    },
    components:{},
    props:{},
    watch:{},
    computed:{},
    methods:{
        save(){
            let formData=new FormData();
            formData.append('name',this.name)
            formData.append('img',this.$refs.file.files[0])
            this.axios.post('/api/user/query',formData,{
                'Content-Type':'multipart/form-data'
            }).then(res=>{
 
            })
        }
    },
    created(){},
    mounted(){}
}
</script>
<style>
</style>


    @PostMapping("/upload_img")
    public String upload_img(@RequestParam(value = "img", required = false) MultipartFile file, @RequestParam("username") String username){

        System.out.println("jin"+username);
        System.out.println("jin");
        if(file != null){
            File f = new File("i:/123.jpg");
            try {
                file.transferTo(f);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("没有上传文件");
        }

        return "upload success";
    }
	**********************************上传单个文件结束********************************
api.js
import axios from 'axios'

let base = '';
export const postRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      // Do whatever you want to transform the data
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
}

export const uploadFileRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}
export const putRequest = (url, params) => {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
}
export const deleteRequest = (url) => {
  return axios({
    method: 'delete',
    url: `${base}${url}`
  });
}
export const getRequest = (url,params) => {
  return axios({
    method: 'get',
    data:params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    url: `${base}${url}`
  });
}

注意事项

注意事项1:
main.js引入axios时应该这样写
Vue.prototype.axios = axios;(正确)
Vue.use(axios);(错误)

注意事项2:
上传文件时如果没有选择文件的话,会报400错误, 要在后端设置require = false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值