请求不包含multipart / form-data或multipart / mixed流,内容类型标头为false

时间:2014-09-07 06:42:09

标签: java javascript jquery ajax file-upload

我想通过ajax发送图像,但我得到以下异常:

org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is false

令人惊讶的是,当我定期发送此表单(而非通过ajax)时,表单工作正常。我尝试将Content-Type更改为multipart / form-data,但后来我得到了这个例外:

org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

这是jquery代码:

$(document).ready(function() {
    $("#myform").submit(function(e) {
       e.preventDefault();
       var data = new FormData();
       data.append('file', document.formName.file.files[0]); // <-- possibly this line doesn't work
       $.ajax({
          url: 'upload.do',
          data: data,
          cache: false,
          contentType: false,
          processData: false,
          type: 'POST',
          success: function(res) {
          }
      });
   });
});

和表格:

 <form name="formName" enctype="multipart/form-data" id="myform" action="upload.do" method="POST">    
   <input type="file"  name="file" id="input-file" /> 
   <br>
   <input type="submit" value="Upload images" class="upload" />
 </form>

1 个答案:

答案 0 :(得分:2)

试试这个:

$(document).ready(function() {
    $('.upload').click(function() {
        var input = document.getElementById('input-file');
        file = input.files[0];
        var data = new FormData();
        data.append('file', file);
        $.ajax({
            url: 'upload.do',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(res) {
            }
        });
    });
});