vue+axios实现文件上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
    <script src="js/vue.js"></script>
    <script src="js/axios-0.18.0.js"></script>
</head>
<body>
<h3> 上传文件a</h3>
<div id="app">
    文件: <input type="file" ref="myfile"> <br/>
    <button @click="addFile"> 点击上传</button>

</div>


<script>
    new Vue({
        el: "#app",
        data() {
            return {}
        },
        methods: {
            addFile() {
                let myfile = this.$refs.myfile;
                console.log("myfile:", myfile);
                let files = myfile.files;
                let file = files[0];
                let formData = new FormData();
                formData.append("uploadFile", file);
                axios.post('/ywb_spring_springmvc_war_exploded/test/p4', formData, {headers: {'Content-Type': 'multipart/form-data'}})
                    .then(res => {
                        console.log(res.data);
                    })
            }
        }


    })

</script>


</body>
</html>

后台接收的Java代码

 @RequestMapping(value = "p4")
    @ResponseBody
    public String p4(@RequestPart MultipartFile uploadFile) throws IOException {
        String name = uploadFile.getOriginalFilename();
        String path = "d://MyFile/";
        File file = new File(path, name);
        Files.copy(uploadFile.getInputStream(), file.toPath());
        return "success";
    }
上一篇:vue写路由遇到的坑


下一篇:Sass wikipedia