Axios跨域+表單提交

1 後端

1.1 Controller

@Controller
public class StudentController {
    private Student student;

    @GetMapping(value = "/get")
    @ResponseBody
    public String get(@RequestParam("stuId") String stuId) {
        if (student == null || !student.getId().equals(stuId)) {
            return "not exists";
        } else {
            return "GET:" + student.toString();
        }
    }

    @PostMapping(value = "/post")
    @ResponseBody
    public String post(@RequestParam("stuId") String stuId,
                       @RequestParam("stuName") String stuName,
                       @RequestParam("stuAge") Integer stuAge) {
        student = new Student().setId(stuId).setName(stuName).setAge(stuAge);
        return "POST:" + student.toString();
    }

    @PostMapping(value = "/upload")
    @ResponseBody
    public String upload(@RequestParam("stuInfos") MultipartFile[] files) {
        if (files.length == 0) {
            return "failed to upload";
        }
        // 保存路徑集合
        List<String> pathnameList = new ArrayList<>();
        // 以日期創建文件夾
        File parentFolder = new File("D:/xyz/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        if (!parentFolder.isDirectory() || !parentFolder.exists()) {
            parentFolder.mkdirs();
        }
        // 保存文件
        for (MultipartFile file : files) {
            String pathname = parentFolder + "/" + file.getOriginalFilename();
            File dest = new File(pathname);
            pathnameList.add(pathname);
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "succeeded to upload at " + pathnameList;
    }
}

1.2 Config

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("*")
                .maxAge(3600);
    }
}

2 前端

2.1 頁面結構

<!DOCTYPE html>
<meta charset="UTF-8">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div class="get-wapper">
    <input type="text" name="stuId">
    <button type="button" onclick="sendGet()">submit-get</button>
</div>

<div class="post-wapper">
    <input type="text" name="stuId">
    <input type="text" name="stuName">
    <input type="text" name="stuAge">
    <button type="button" onclick="sendPost()">submit-post</button>
</div>

<div class="upload-wrapper">
    <input type="file" name="stuInfos" multiple="multiple">
    <button type="button" onclick="sendUpload()">submit-upload</button>
</div>

2.2 AJAX

// GET 請求
function sendGet() {
    let data = { 'stuId': document.getElementsByName('stuId')[0].value };
    axios({
        url: 'http://127.0.0.1:8080/get',
        method: 'GET',
        params: data
    }).then(response => console.log(response.data)).catch(error => console.log(error));
}

// POST 請求
function sendPost() {
    let data = new URLSearchParams();
    data.append('stuId', document.getElementsByName('stuId')[1].value);
    data.append('stuName', document.getElementsByName('stuName')[0].value);
    data.append('stuAge', document.getElementsByName('stuAge')[0].value);
    axios({
        url: 'http://127.0.0.1:8080/post',
        method: 'POST',
        data: data,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Access-Control-Allow-Headers': 'Content-Type, Content-Length,Authorization, Accept, X-Requested-With'
        }
    }).then(response => console.log(response.data)).catch(error => console.log(error));
}

// 上傳文件
function sendUpload() {
    let data = new FormData();
    for (let file of document.getElementsByName('stuInfos')[0].files) {
        data.append('stuInfos', file);
    }
    axios({
        url: 'http://127.0.0.1:8080/upload',
        method: 'POST',
        data: data,
        headers: {
            'Content-Type': 'multipart/form-data',
            'Access-Control-Allow-Headers': 'Content-Type, Content-Length,Authorization, Accept, X-Requested-With'
        }
    }).then(response => console.log(response.data)).catch(error => console.log(error));
}

3 注意事項總結

3.1 Springboot上傳文件大小限制

Springboot默認單文件大小限制爲 1MB, 總文件大小限制爲 10MB,可以在 application.properties 裏進行配置:

# 單文件大小限制
spring.servlet.multipart.max-file-size=10MB
# 總文件大小限制
spring.servlet.multipart.max-request-size=100MB

3.2 Webpack編譯自定義函數調用

使用 Webpack 打包後的函數屬於模塊內部變量,然而即便將它們暴露出去也無法被 html 訪問。所以如果只是單純的使用 Webpack 來編譯,可以在定義函數時將其作用域提升:

import axios from 'axios';

window.sendGet = function () {
    let data = { 'stuId': document.getElementsByName('stuId')[0].value };
    axios({
        url: 'http://127.0.0.1:8080/get',
        method: 'GET',
        params: data
    }).then(response => console.log(response.data)).catch(error => console.log(error));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章