SpringBoot二、jQuery上传文件

一、HTML


上传图书封面图片

二、JS

$("#photopath").change(function () {
        /*图片类型正则验证*/
        var imgStr = /\.(jpg|jpeg|png|bmp|BMP|JPG|PNG|JPEG)$/;
        if(!imgStr.test($(this).val())) {
            alert("文件不是图片类型");
            $(this).val('');
        } else {
            var url = $("#header").attr("data-context-url");
            var formData = new FormData($("#publishForm")[0])
            $.ajax({
                url : url + 'publishUpload',
                type : 'post',
                data : formData,
                processData: false,
                contentType: false,
                success : function (data) {
                    console.log(data);
                    // 图片回显
                    $("#photopath_img").attr("src", data);
                }
            });
        }
    });

三、Java

@PostMapping("publishUpload")
    @ResponseBody
    public String publishUpload(MultipartFile photopath, HttpSession session) throws IOException {
        //String contentType = photopath.getContentType();
        // 使用UUID生成随机文件名
        String fileName = UUID.randomUUID() + "." + photopath.getOriginalFilename().split("\\.")[1];
        // 获取项目路径 + 静态文件存放路径
        String filePath = session.getServletContext().getRealPath("images/book/");

        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        // 将文件写入到filepath路径下
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(photopath.getBytes());
        out.flush();
        out.close();
        //返回json
        return "images/book/" + fileName;
    }

 

你可能感兴趣的:(Spring,Boot)