Ajax成功和错误回调永远不会被解雇

时间:2016-01-24 14:03:02

标签: jquery ajax jsp servlets

我已经搜索过高低的答案,但没有任何效果。我正在尝试使用ajax将图像上传到服务器,一旦图像上传,服务器应返回图像的路径,然后显示在屏幕上。上传工作正常,但由于成功(甚至不是错误)回调永远不会被触发,我无法将上传的图像显示给用户(因为我希望在成功回调中得到结果)。

JSP

<form id="uploadData" action="UploadPhoto" method="post"   enctype="multipart/form-data">
<input   type="file" onchange="fileChanged('postImg')" name="postImg"    id="postImg" ><br>
<input type="submit" value="Upload image" > 
</form>

的Ajax

$(function(){
$(document).ready(function(){
  $('#uploadData').ajaxForm(
                  {

                    success: function(data,status,xhr) {
                    alert("...success uploading image..."+status);
                        var dataMessage = data.split('|');
                        var isError = dataMessage[0] == "true" ? true : false;
                        var errorMessage = dataMessage[1];
                        var imageUrl = dataMessage[2];
                        //this should display the image
                            $("#postContent").htmlarea("image", "${pageContext.request.contextPath}/img/"+imageUrl);                 
                    },
                    error: function(errorMsg){
                         alert("...error uploading image..."+errorMsg);

                    },

                }
            );  
            });

});

的Servlet

    Map<String,String> multipartItems = null;
    if((multipartItems=processMultiformatData(request))==null)
        return;

    String userImg = multipartItems.get("postImg");
    //response.setContentType("text/html");//tried this one too
    response.setContentType("text/plain");

    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write(userImg);

ajax调用后Chrome中的响应

Request URL:http://localhost:8080/SomeSite/UploadPhoto
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:8080
Response Headers
view source
Content-Length:12
Content-Type:text/plain
Date:Sun, 24 Jan 2016 12:46:56 GMT
Server:Apache-Coyote/1.1
Request Headers
view source 
 Accept:text/html,application/xhtml+xml,
application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:2997
Content-Type:multipart/form-data; boundary=----       WebKitFormBoundaryBLLyr0fgnS47WfqA
Cookie:JSESSIONID=03BC5363F392EB58FB043B87B5289733
Chrome/47.0.2526.111 Safari/537.36
Request Payload
------WebKitFormBoundaryBLLyr0fgnS47WfqA
Content-Disposition: form-data; name="postImg"; filename="4-128[1].png"
Content-Type: image/png

我确实在响应中获得了路径,但由于永远不会调用成功回调,因此我无法在屏幕上显示它(作为img标记的一部分)。

感谢任何帮助。

编辑:当然,因为我知道我正在发送的图像的名称,服务器路径总是相同的(路径+图像)我可以使用此信息显示图像,如果其他一切都失败。

0 个答案:

没有答案