使用ajax+Springboot实现文件上传

使用ajax+Springboot实现文件上传,第1张

后端部分:
@PostMapping("/fileUpload")
    public Map<String,Object> getFile(@RequestPart("file") MultipartFile file) throws IOException {
        if(!file.isEmpty())
        {
            // 获取文件名
            System.out.println(file.getName());
            // 获取原始文件路径
            System.out.println(file.getOriginalFilename());
            // 文件存储
            File file1 = new File("C:\Users\NLER\IdeaProjects\uploadDemo1\file\"+file.getOriginalFilename());
            FileOutputStream stream = new FileOutputStream(file1);
            byte[] bytes = file.getBytes();
            stream.write(bytes);
            stream.close();
            Map<String,Object> map = new HashMap<>();
            map.put("code",200);
            map.put("result","请求成功");
            return map;
        }
        else
        {
            Map<String,Object> map = new HashMap<>();
            map.put("code",500);
            map.put("result","请求失败");
            return map;
        }
    }
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="uploadData">
        <form id="form" action="/fileUpload" method="post" enctype="multipart/form-data">
         <input id="file" type="file" name="file" value="请选择文件">
        </form>
        <button @click="upload">上传</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script>
        var MyVue1 = new Vue({
            el:'#uploadData',
            data:{},
            methods:{
                upload()
                {
                    // console.log(document.getElementById("file").files[0]);
                    // 使用formdata传递信息
                    var formData = new FormData($('#form')[0]);
                    $.ajax({
                        url:'http://localhost:8080/fileUpload',
                        // contentType:"multipart/form-data",
                        contentType: false,
                        method: "POST",
                        processData:false,
                        data:formData,
                        // data:document.forms['form'],
                        // data:document.getElementById('file').files[0],
                        success:(e)=>{
                            console.log(e)
                        }
                    })
                    console.log("测试")
                }
            }
        })
    </script>
</body>
</html>

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/739506.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存