美文网首页开发中的小问题解决
@RequestPart 解决同时上传文件和json的解决方案

@RequestPart 解决同时上传文件和json的解决方案

作者: eagle隼 | 来源:发表于2018-08-21 19:05 被阅读0次

之前公司有一个上传功能是带有业务逻辑的,除了文件之外还有一个json信息的请求,当时是把json信息当成字符串用param方式传递给后台,后台再手动序列化一直觉得不太优雅,专研许久使用@RequestPart 解决了问题但是其中前后端都有一些需要注意的地方,话不多说上源码

前端

<body>
    <input type="file" id="file" name="file"/>
    <button id="button" name="">上传</button>
</body>


$(function () {
    $("#button").click(function () {
        //构建formData
        var formData = new FormData();
        //文件部分
        var file = document.getElementById("file").files[0];
        formData.append("file", file);
        //json部分
        var imageInfo = JSON.stringify({
            "width": "240",
            "height": "320"
        });
        //这里包装 可以直接转换成对象
        formData.append('imageInfo', new Blob([imageInfo], {type: "application/json"}));

        $.ajax({
            url: "/test/upload",
            type: "post",
            //忽略contentType
            contentType: false,
            //取消序列换 formData本来就是序列化好的
            processData: false,
            dataType: "json",
            data: formData,
            success: function (response) {
                alert(response);
            },
            error: function () {

            }
        });
    });
})

后端

@PostMapping("upload")
public ImageInfo upload(@RequestPart("file") MultipartFile file,@RequestPart("imageInfo") ImageInfo imageInfo) {
    System.out.println(imageInfo);
    return imageInfo;
}

相关文章

网友评论

    本文标题:@RequestPart 解决同时上传文件和json的解决方案

    本文链接:https://www.haomeiwen.com/subject/ijajiftx.html