• axios get/post/delete上传下载及springboot后端示例


    简介

    记录axios各种使用方法,包括get/post/delete上传下载多种写法及springboot后端示例

    正文

    以下示例基于浏览器环境,直接使用html直接引入axios资源

    <script src="https://cdn.jsdelivr.net/npm/axios@1.5.0/dist/axios.min.js"></script>
    
    • 1

    1.get 请求示例

    // 假设有一个查询字符串参数对象
    const params = {
      key1: 'value1',
      key2: 'value2'
    };
    
    axios.get('/api/data', {
      params: params
    })
    .then(response => {
      console.log('Data:', response.data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    2.post 请求示例

    三种类型的Content-Type 请求方式

    2.1 JSON 格式数据(最常用)

    • Content-Type: application/json
    import axios from 'axios'
    let data = {"code":"1234","name":"yyyy"};
    axios.post(`${this.$url}/test/testRequest`,data)
    .then(res=>{
        console.log('res=>',res);            
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.2 FormData 数据格式(用于上传文件等场景)

    • Content-Type: multipart/form-data
    // 创建 FormData 对象并添加数据
    const formData = new FormData();
    formData.append('file', file); // 假设 file 是一个文件对象
    formData.append('path', '/root/tmp') // 文本字段
    axios.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then(response => {
      console.log('Response:', response.data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    2.3 x-www-form-urlencoded 数据格式(比较少用)

    • Content-Type: application/x-www-form-urlencoded

    示例1:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>POST Request with x-www-form-urlencoded</title>
    </head>
    
    <body>
        <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/qs/dist/qs.js"></script>
    
        <script>
            function sendData() {
                const data = {
                    key1: 'value1',
                    key2: 'value2'
                };
    
                // 转换为 x-www-form-urlencoded 格式
                const formData = qs.stringify(data);
    
                // 发送 POST 请求
                axios.post('/api/data', formData, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(response => {
                    console.log('Response:', response.data);
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            }
    
            // 调用函数发送数据
            sendData();
        </script>
    </body>
    
    </html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    3.4 知识点: multipart/form-data 和 application/x-www-form-urlencoded 有什么区别和联系

    ultipart/form-data 和 application/x-www-form-urlencoded 都是常见的 POST 请求数据提交方式,它们在数据格式上有一些区别和使用场景上的差异

    特点application/x-www-form-urlencodedmultipart/form-data
    数据格式键值对形式(key-value pairs),使用 &= 连接多部分数据,每部分有唯一的边界标识(boundary)
    适用场景简单文本数据上传文件、包含大量文本数据、二进制数据
    数据编码文本数据会被编码(URL-encoded)二进制数据直接传输,不编码
    用途适用于表单提交、简单文本数据传输等适用于上传文件、图像、视频等二进制数据传输
    性能对文本数据编码,可能导致数据变得冗长直接传输二进制数据,更高效
    示例key1=value1&key2=value2多部分数据,每部分包含字段名、字段值、边界标识等

    区别和联系:

    • 数据格式: application/x-www-form-urlencoded 是以简单的键值对形式传输数据,而 multipart/form-data 允许传输更复杂的数据结构,包括文件和其他二进制数据。

    • 性能: application/x-www-form-urlencoded 对文本数据进行编码,可能会导致数据变得冗长,而 multipart/form-data 可以直接传输二进制数据,更高效。

    • 用途: application/x-www-form-urlencoded 适用于简单文本数据的传输,而 multipart/form-data 适用于文件上传和传输包含大量文本数据的场景。

    在实际应用中,选择合适的格式取决于数据类型和需求。如果你需要传输文件或其他二进制数据,使用 multipart/form-data 格式。如果只需要传输简单的文本数据,application/x-www-form-urlencoded 格式通常足够了。

    3. delete 请求示例

    当发送 DELETE 请求时,你可以在 URL 中包含参数,也可以将参数放在请求体中。以下是带有参数的 DELETE 请求示例

    3.1 url带参数方式

    前端代码
    const axios = require('axios');
    
    // 发送带有 URL 参数的 DELETE 请求
    axios.delete('/api/resource?id=123')
    .then(response => {
      console.log('Response:', response.data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    有时候多个请求参数需要手动拼接参数可读性较差,写起来也麻烦.也可以使用params参数来替代,传递一个对象Axios 会自动将其拼接到 URL 后

    const axios = require('axios');
    
    const id = 123;
    
    axios.delete('/api/resource', {
      params: {
        id: id
      }
    })
    .then(response => {
      console.log('Response:', response.data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    后端代码

    带有URL参数的DELETE请求处理(使用@PathVariable或@RequestParam)

    • @PathVariable 方式
    @RestController
    public class MyController {
    
        @DeleteMapping("/api/resource/{id}")
        public ResponseEntity<String> deleteResourceById(@PathVariable Long id) {
            // 处理逻辑...
            return ResponseEntity.ok("Resource with ID " + id + " deleted successfully");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • @RequestParam
    @RestController
    public class MyController {
    
        @DeleteMapping("/api/resource")
        public ResponseEntity<String> deleteResourceById(@RequestParam Long id) {
            // 处理逻辑...
            return ResponseEntity.ok("Resource with ID " + id + " deleted successfully");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3.2 请求体参数方式

    前端
     const axios = require('axios');
    
    // 发送带有请求体参数的 DELETE 请求
    const data = {
      id: 123
    };
    
    axios.delete('/api/resource', {
      data: data
    })
    .then(response => {
      console.log('Response:', response.data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    后端
    @RestController
    public class MyController {
    
        @DeleteMapping("/api/resource")
        public ResponseEntity<String> deleteResource(@RequestBody DeleteRequest deleteRequest) {
            Long id = deleteRequest.getId();
            // 处理逻辑...
            return ResponseEntity.ok("Resource with ID " + id + " deleted successfully");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    4.上传/下载

    4.1 文件上传

      beforeUpload(file) {
          var vm = this
          // 将文件添加到请求数据中
          const formData = new FormData();
          formData.append('file', file);
          formData.append('remoteDirectory', this.sftp.upload.form.path);
          formData.append('serverName', this.serverAttribute.currentServer)
    
          axios.post(this.sftp.upload.url, formData, {
                  // 监听文件上传进度
                  onUploadProgress: (progressEvent) => {
                      const { loaded, total } = progressEvent;
                      const progress = Math.round((loaded / total) * 100);
                      console.log(`Upload Progress: ${progress}%`);
                      vm.sftp.upload.uploading = true;
                      vm.sftp.upload.uploadProgress = progress;
                  },
    
              })
              .then(response => {
                  console.log('File uploaded successfully', response);
                  vm.loadSftpFile(this.serverAttribute.currentServer, this.sftp.upload.form.path);
                  // 重置进度条状态
                  vm.sftp.upload.uploading = false
                  vm.sftp.upload.uploadProgress = 0
              })
              .catch(error => {
                  console.error('Error uploading file', error);
              });
    
          return false; // 阻止默认上传行为
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    4.2 文件下载

    vm.$Modal.confirm({
        title: '是否确认下载',
        content: '

    '+ record.fileName+ '

    '
    , onOk: () => { // 创建一个隐藏的标签 const link = document.createElement('a'); link.href = vm.baseUrl + '/web-ssh/sftpFile/download?serverName=' + vm.serverAttribute.currentServer + '&remoteFilePath=' + this.sftp.upload.form.path + '/' + record.fileName; // 设置下载属性,以便浏览器弹出下载对话框 link.setAttribute('download', record.simpleObjectName); // 模拟点击事件来触发下载 link.click(); }, onCancel: () => { //this.$Message.info('Clicked cancel'); } });

    4.3 后端接口

    @Controller
    @RequestMapping("/web-ssh")
    public class WebSShController {
        private static final Logger LOGGER = LoggerFactory.getLogger(WebSShController.class);
    
        @Autowired
        private WebSSHProperties webSSHProperties;
    
        @GetMapping("/server")
        @ResponseBody
        public List<SSHConfig> listServer() {
            return webSSHProperties.getServer();
        }
    
        private Map<String, SftpClient> clientMap = new HashMap<>();
    
        @GetMapping("/sftpFile/list")
        @ResponseBody
        public Map<String, Object> listSftpFileInfo(String serverName, String parentPath) throws SftpException {
            SftpClient sftpClient = clientMap.get(serverName);
            if (sftpClient == null) {
                sftpClient = new SftpClient(webSSHProperties.getSshInfo(serverName));
                clientMap.put(serverName, sftpClient);
                sftpClient.connection();
            }
    
            // 获取sftp连接
            parentPath = parentPath.endsWith("/") ? parentPath: parentPath + "/";
            List<SftpFileInfo> fileInfoList = sftpClient.list(parentPath);
    
            // 模拟使用池化的对象不关闭
            //sftpClient.close();
    
            Map<String, Object> result = new HashMap<>();
            result.put("data", fileInfoList);
            return result;
        }
    
    
        @PostMapping(value = "/sftpFile/upload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
        @ResponseBody
        public ResponseEntity<SftpFileInfo> uploadFile(String serverName, @RequestParam("file") MultipartFile file, String remoteDirectory) throws Exception {
            remoteDirectory = remoteDirectory.endsWith("/") ? remoteDirectory: remoteDirectory + "/";
            SftpClient sftpClient = new SftpClient(webSSHProperties.getSshInfo(serverName));
            sftpClient.connection();
    
            String remoteFileName = file.getOriginalFilename();
            // 上传文件到远程主机
            InputStream inputStream = file.getInputStream();
            sftpClient.upload(inputStream, remoteDirectory, remoteFileName);
            sftpClient.close();
            return ResponseEntity.ok(null);
        }
    
    
        @GetMapping(value = "/sftpFile/download", produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE})
        public void downloadFile(String serverName, HttpServletResponse response, String remoteFilePath) throws Exception {
            String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf('/') + 1);
            LOGGER.info("[web-ssh] sftp download file[{}] from[{}]", remoteFilePath, serverName);
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    
            SftpClient sftpClient = new SftpClient(webSSHProperties.getSshInfo(serverName));
            sftpClient.connection();
            // 获取远程文件内容
            try (InputStream remoteFileInputStream = sftpClient.download(remoteFilePath);
                 OutputStream outputStream = response.getOutputStream()) {
                IOUtils.copy(remoteFileInputStream, outputStream);
            }
            sftpClient.close();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    参考文档

    1. axios POST提交数据的三种请求方式写法

    附录

    1. 非axios实现上传

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>File Upload with iView and Vue.jstitle>
    
        
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js">script>
    
        
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/iview@3.5.1/dist/styles/iview.css">
    
        
        <script src="https://cdn.jsdelivr.net/npm/iview@3.5.1/dist/iview.min.js">script>
    head>
    <body>
    <div id="app">
        <div>
            <input type="file" ref="fileInput" @change="handleFileChange" />
            <button @click="uploadFile">上传button>
        div>
    div>
    
    <script>
        new Vue({
            el: '#app',
            data: {
                selectedFile: null
            },
            methods: {
                handleFileChange(event) {
                    this.selectedFile = event.target.files[0];
                },
                uploadFile() {
                    const formData = new FormData();
                    formData.append('file', this.selectedFile);
    
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', '/admin/storage/file', true);
                    xhr.onreadystatechange = () => {
                        if (xhr.readyState === XMLHttpRequest.DONE) {
                            if (xhr.status === 200) {
                                console.log('File uploaded successfully');
                            } else {
                                console.error('Error uploading file');
                            }
                        }
                    };
                    xhr.send(formData);
                }
            }
        });
    script>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
  • 相关阅读:
    循环神经网络 - 通过时间反向传播
    【Python】第一课 Python环境搭建
    Dapr(一) 基于云原生了解Dapr
    12.并发之ForkJoin框架详解
    Biotinyl-εAhx-Amyloid β-Protein (1-42),CAS: 1872440-40-8
    水声信号调制方式智能识别技术
    链表单向链表跳跃链表
    12-资源注解annotations和安全行下文securityContext(了解即可)
    简单的Web前端数据字典实现,小型项目必备
    win10 xbox录屏功能不能录声音怎么办
  • 原文地址:https://blog.csdn.net/Myron_007/article/details/133706639