jQuery上传文件的方法


<div id="login-form"> <!--<form id="uploadSongsForm" method="POST" action="/upload" enctype="multipart/form-data">--> <form id="uploadSongsForm" enctype="multipart/form-data"> <div id="showMp3Files" class="tittle" > <div class=" form-group"> <input type="file" name="file" id="mp3Files" > </div> <div class=" form-group"> <button type="reset" id="clearmp3" class="btn btn-dark">清除选择歌曲</button> </div> <div class=" form-group"> <input type="submit" value="上传" id="uploadBtn" class=" btn btn-primary" > </div> </div> </form>

jq代码

 $("#uploadSongsForm").submit(function () {
            $.post("/upload",{file:file},function (info) {
                if(info.flag){
                    alert(info.msg)
                }else{
                    //添加失败
                    alert(info.msg);
                }
            });
            return false;

        });

controller代码

 private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public ResultInfo upload(@RequestParam("file") MultipartFile file) {
        ResultInfo info=new ResultInfo();
        info.setFlag(false);
        if (file.isEmpty()) {
            info.setMsg("文件为空");
            info.setFlag(false);
            return info;
        }

        String fileName = file.getOriginalFilename();
        String filePath = "/mp3/";
        System.out.println("文件名:"+fileName);
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("succeed");
            info.setFlag(true);
            info.setMsg("上传成功");
            return info;
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        info.setMsg("上传失败");
        return info;
    }

就我的猜测是jq段肯定是有错误的。

试着修改过来。

jq的ajax方法:

  $(window).ready(function () {
            $("#uploadBtn").click(function () {
                var formData=new FormData($("#uploadSongsForm")[0]);
                alert(formData);
                $.ajax({
                    url:"/upload",
                    type:"post",
                    data:formData,
                    cache:false,
                    processData: false,
                    contentType: false,
                    success:function (str) {
                        alert(str);
                    },
                    erro:
                    function (str) {
                        alert(str)
                    }


                    }
                )
            })
        })

这个好处就是,F12,请求的路径都不显示在浏览器里。

 

 
上一篇:原生JS上传大文件实例解析


下一篇:上传组件upload