qq_26290227
蓝胧月
2019-12-18 11:04
采纳率: 66.7%
浏览 288

ajax同时上传xlsx文件和1条字符串,参数怎么传递

单独上传xlsx没有问题,但是多加一条字符串报错:org.springframework.web.multipart.MultipartException: The current request is not a multipart request

以下是我的代码:

jsp:

<div class="btn-file col-md-6">
    <button id="btn_upload" type="button" class="btn btn-success" style="width: 100px;margin-right: 20px">
        <i class="fa fa-cloud-upload" aria-hidden="true"></i> 文件上传
    </button>
</div>

js:

$("#btn_upload").on("click", function () {
    var date = $("#date").val();
    var s = document.getElementById("fileUpload");
    if (s !== undefined) {
        $("#fileUpload").remove();
    }
    var inputObj = document.createElement('input');
    inputObj.setAttribute('id', 'fileUpload');
    inputObj.setAttribute('type', 'file');
    inputObj.setAttribute('name', 'file');
    inputObj.setAttribute('accept', '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel');
    inputObj.setAttribute("style", 'visibility:hidden');
    document.body.appendChild(inputObj);
    inputObj.click();
    $("#fileUpload").on('change', function () {
        $("#inputText1").val(this.files[0].name);
        if ($("#fileUpload").val() !== "") {
            var formData = new FormData();
            formData.append("file",this.files[0]);
            $.ajax({
                type: "post",
                url: appName + '/report/upload.do',
                data: {
                    data:data,
                    file:formData
                },
                dataType: "text",
                processData: false,
                contentType: false,
                success: function (result) {
                if (result == "success"){
                    layer.msg("提交成功!", {icon: 6, time: 3000});
                }  else {
                    layer.msg("提交失败!", {icon: 2, time: 3000});
                }
                },
                error: function () {
                    layer.msg("请求失败!", {icon: 2, time: 3000});
                }
            });
            layer.msg('文件上传!', {icon: 1, time: 3000});
        } else {
            layer.msg("请先选择文件!");
        }
        });
        });

controller:

@RequestMapping(value="/upload.do")
    @ResponseBody
    public String upload(String date, MultipartFile file) throws IOException {
        String path = "F:\\upload";
        String fileName = file.getOriginalFilename();
        File dir = new File(path,fileName);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //MultipartFile自带的解析方法
        file.transferTo(dir);
        System.out.println(date);
        System.out.println(fileName);
        return "fail";
    }
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • wojiushiwo945you
    毕小宝 2019-12-18 11:17
    已采纳

    首先,有文件表单和普通文本表单,那么 dataType: "text", 设置的应该是有问题,应该用 Multi-data 类型的吧。
    其次,data 配置的 name 是 data ,而 Controller 中的参数是 date 不一致。

    点赞 评论

相关推荐