Ajax上传图片,后台使用SpringBoot的MultipartFile类型接收的问题

Ajax很好用,但是在上传文件这边却总是会出问题。例如,现在想上传一张图片,希望前台无刷新操作,使用Ajax上传,后台接收不到相应的类型,导致上传失败,但是如果使用input和submit组合又会出现页面刷新的情况,百般折磨后找到了一个新的工具:Simple-Ajax-Uploader.

简单示例

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button id="btnUpload">上传图片</button>
<script type="text/javascript" src="SimpleAjaxUploader.js"></script>
<script type="text/javascript">
    var btnUpload = document.getElementById("btnUpload");
    var uploader = new ss.SimpleUpload({
        button: btnUpload,
        url: "http://192.168.1.105:8080/api/file/upload/image",
        name: "uploadImage",
        multiple: true,
        allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
        responseType: 'json',
        onSubmit: function () {

        },
        onComplete: function (filename, response) {
            console.log(filename);
            console.log(response);
        },
        onError: function (error) {
            console.log(error);
        }
    });
</script>
</body>
</html>

后台代码

    /**
     * 单张图片上传接口
     *
     * @param request     请求
     * @param uploadImage 要上传的图片
     * @return 上传成功返回图片的URL;上传失败返回“上传失败”;
     */
    @ApiOperation(value = "单张图片上传接口")
    @RequestMapping(value = "/upload/image", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public HttpResponse<String> uploadImage(HttpServletRequest request, MultipartFile uploadImage) {
        HttpResponse<String> httpResponse = new HttpResponse<>();
        if (null != uploadImage) {
            String uploadImagePath = request.getSession().getServletContext().getRealPath("/") + "/file/upload/image/";
            File uploadImageDir = new File(uploadImagePath);
            if (!uploadImageDir.exists()) {
                boolean success = uploadImageDir.mkdir();
                if (success) {
                    System.out.println("文件夹创建成功");
                } else {
                    System.out.println("文件夹创建失败");
                }
            }
            // 初始化图片信息
            Image image = initImage(uploadImage);
            // 要保存的图片
            File saveToServerImage = new File(uploadImagePath + image.getName());
            try {
                // 将要上传的图片信息写入要保存的图片中
                uploadImage.transferTo(saveToServerImage);
                // 将图片信息存储到数据库
                Image saveToDbImage = imageJPA.save(image);
                if (null != saveToDbImage) {
                    httpResponse.setCode(1);
                    httpResponse.setData(saveToDbImage.getUrl());
                    httpResponse.setMsg("图片上传成功");
                    return httpResponse;
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        httpResponse.setCode(0);
        httpResponse.setData("");
        httpResponse.setMsg("图片上传失败");
        return httpResponse;
    }

这样就可以无刷新解决问题啦。


upload.gif
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,593评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,268评论 19 139
  • 李重凰阅读 264评论 0 1
  • 第五目没有写关于文章的内容,反而介绍起阅读的书籍了。 事情的起因是中秋节到了,大文和乐华两家人一起过中秋,刚好大文...
    kww007阅读 490评论 0 0
  • 今天结合市调继续学习稻盛和夫案例。 在稻盛和夫的著作《活法》中稻盛先生阐述了一种被称为“智慧之井”的地方。当一个人...
    快乐稀饭阅读 397评论 0 0