我发现用AJAX上传图像似乎不符合表单中指定的multipart,因为我检查它是否为multipart()的代码从不起作用(在Java中)。
if (context.isMultiPart() { System.out.println("received Multipart data"); } else { System.out.println("not multipart data!"); /* my code always prints this message in the upload handler uploadPost() */ }
我有这个HTML表单:
<div class="title"><label>Upload picture!</label></div> <form method="post" id="imageUploadForm" enctype="multipart/form-data" action="/uploadPost"> Please specify file to upload: <input type="file" name="upfile"><br /> <input type="submit" value="submit" id="submitButton"> </form> <div id="imagedisplay"> </div>
以下是我的Ajax代码,该代码将图像发送到地址处的上传处理程序/uploadPost。我的Java代码中的uploadPost()方法首先确定上传是否为多部分,但是,似乎ajax不会将图像作为多部分发送。是否因为我在表单上使用了jQuery的serialize()方法?
/uploadPost
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function() { $('#imageUploadForm').submit(function(evt) { var formData = $('#imageUploadForm').serialize(); $.post('/uploadPost', formData, uploadResults); evt.preventDefault(); }); // display the uploaded image on the same page function uploadResults(data) { $('#imagedisplay').html("<img src=" + data.url + "" + data.name + ">"); } // end of uploadResults }); // end of ready </script>
从serialize()更改为以下代码对我有用:
$('#imageUploadForm').submit(function(evt) { evt.preventDefault(); var formData = new FormData(this); $.ajax({ type: 'POST', url: $(this).attr('action'), data:formData, cache:false, contentType: false, processData: false, success: function(data) { $('#imagedisplay').html("<img src=" + data.url + "" + data.name + ">"); }, error: function(data) { $('#imagedisplay').html("<h2>this file type is not supported</h2>"); } }); });