0

I am using ajaxupload.js from here and I see the file doing the upload work alright. But I am getting <pre style="word-wrap: break-word; white-space: pre-wrap;">{"id":"006","path":"006.png"}</pre> in the response.

I think the response should be just {"id":"006","path":"006.png"} but for some reasons it got wrapped around <pre> and hence the Uncaught SyntaxError: Unexpected token <.

I am using spring mvc 3, tomcat. I am using java.io.Writer to write the response as writer.write(json.toString());

Could someone help me understand this error and how to resolve it?

Thanks.

UPDATE:

CODE:

<form id="app-form" class="cols" action="#" method="POST">
    <fieldset class="w50">                              
        <!--  set of form fields -->
    </fieldset>   
    <fieldset class="w50">                              
        <button id="uploadButton" class="csbutton-grey" >Upload</button>
        <ul id="locationImages"></ul>
    </fieldset>
<div style="float: left;">
    <button type="submit" class="cool-button">Submit</button>
</div>
</form>


$(document).ready(function(){
    var button = $('#uploadButton'), interval;

    new AjaxUpload(button, {
        action: 'uploadImage', 
        name: 'qqfile',
        responseType: "json",
        onSubmit : function(file, ext){
            this.disable();
            console.log("file - " + file);
            console.log("ext - " + ext);
            if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
                alert('Error: invalid file extension');
                return false; 
            }
            else {
                $.ajax({
                    type:"GET",
                    url:"file",
                    data:'file='+file,
                    success:function(data, textStatus, jqXHR){
                        console.log(jqXHR.status);
                        console.log(data);
                    },
                    error:function(jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR.status);
                    },
                });                 
            }
        },
        onComplete: function(file, response){
            this.enable();
            console.log("file - " + file);
            console.log("response.id - " + response.id + ", response.path - " + response.path);
            $('<li></li>').appendTo('#locationImages').text(file);                      
        }
    }); 
});
skip
  • 12,193
  • 32
  • 113
  • 153

2 Answers2

1

If you want to send JSON to the client, use Jackson. Spring MVC had native support for it. Create a bean class like this:

public class Result{
private String id;
private String path;
public Result(String id, String path){
this.id=id;this.path=path;}
public Result(){}
// add getters and setters
}

Now create your controller method like this

@ResponseBody // this is important
@RequestMapping("/path/to/mapping")
public Result someMethodName(SomeParameter param1, SomeParameter param2){
    // do something here
    return new Result(id, path);
}

As long as you have Jackson on your classpath and have configured your Spring app through <mvc:annotation-config />, this will automatically serialize your response Object to correct JSON (including correct mime type)

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • Yep. That is what I always use for returning json data, but with https://github.com/valums/ajax-upload I am getting `java.lang.IllegalStateException: getWriter() has already been called for this response at org.apache.catalina.connector.Response.getOutputStream(Response.java:580) at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:183) at org.springframework.http.server.ServletServerHttpResponse.getBody(ServletServerHttpResponse.java:71) ...` :( – skip Jun 05 '12 at 10:23
1

Have you set the responseType property as json in AjaxUpload?

Dandy
  • 692
  • 4
  • 7
  • I totally missed to set that. Now that have done it that error was gone but I am getting `[object Object]` for response and a new error came for which I had to replace ` ` to ` ` to work around it, otherwise IE 8 was not happy and the styling of the page went awry with it. And `https://github.com/valums/ajax-upload` is not working with IE 8 or Mozilla 9 :(. – skip Jun 05 '12 at 10:16
  • But working with Safari 5.1.4 and Chrome 19.0.1084.52 m. I am getting `[object Object]` for response and It is notworking with IE 8 or Mozilla 9. What do I do? I am using https://github.com/valums/ajax-upload. – skip Jun 05 '12 at 10:17
  • 1
    If you alert a json object, you will get [object Object]. This means you have got the proper object back. You can try alerting obj.id, obj.path to see if you are getting the proper values. – Dandy Jun 05 '12 at 10:23
  • Oh damn. Yep, I just got the value extracted from the response. What do I do with Mozilla and IE? They both give me `HTTP Status 405 - Request method 'POST' not supported`. Sometimes even Chrome 19 does that too. What could I be doing wrong? – skip Jun 05 '12 at 10:31
  • Have added the code in the post as an update. I get http://wikedlynotsmat.com/current-form-page.html# for the url and get HTTP Status 405 - Request method 'POST' not supported for the error when I click on Upload button. – skip Jun 05 '12 at 12:31
  • The url I get directed to is the the url of the current page with `#` appended to it. So if the form page where I have the upload option as well is on `wikedlynotsmat.com/current-form-page.html` then when I click on the `Upload` button I get redirected to `wikedlynotsmat.com/current-form-page.html#` with `HTTP Status 405 - Request method 'POST' not supported` meesage. Sorry for the url confusion earlier in case you noticed them during comment updates. Thanks again. – skip Jun 05 '12 at 12:40
  • If I change the upload element in html file to `
    Upload
      ` then I see that it is no more clickable in firefox 9 and IE 8 but works with both chrome 19 and safari 5.
      – skip Jun 05 '12 at 12:59