Different encoding of an HTTP request result, depending on the Accept header

爱⌒轻易说出口 提交于 2019-12-25 15:17:32

问题


I have a controller with a method to upload files, using, on the client side, the dojo Uploader class that supports ajax uploads for all browsers except IE, and uploads with an IFrame for IE. The result is a JSON object, but when the IFrame mechanism is used, the JSON must be enclosed in a <textarea>:

@RequestMapping(value = "/documentation/{appId:.+}/", method = RequestMethod.POST)
@ResponseBody
public String uploadDocumentation(HttpServletRequest request,
        @PathVariable String appId, @RequestParam("uploadedfile") MultipartFile file)
        throws Exception {
    // ....
    String json = JsonUtils.jsonify(map);
    if (accepts(request, "application/json")) {
                return json;
    } else if (accepts(request, "text/html")) {
        return "<textarea>" + json + "</textarea>";
    } else {
        throw new GinaException("Type de retour non supporté");
    }

I was wondering if there is a way to register this encoding mechanism in the framework, so that we would just have to return an object, and let the framework do the rest.

Thanks in advance.


回答1:


For the record, I simply added a second method:

@RequestMapping(value = "/documentation/{appId:.+}/", method = RequestMethod.POST,
        produces="application/json")
@ResponseBody    
public UploadResult uploadDocumentation(@PathVariable String appId,
         @RequestParam("uploadedfile") MultipartFile file) throws Exception {
    ...
    return new UploadResult(filename);
}

@RequestMapping(value = "/documentation/{appId:.+}/", method = RequestMethod.POST,
        produces="text/html")
@ResponseBody    
public String uploadDocumentationIE(@PathVariable String appId,
        @RequestParam("uploadedfile") MultipartFile file) throws Exception {
    UploadResult obj = uploadDocumentation(appId, file);
    String json = JsonUtils.jsonify(obj);
    return "<textarea>" + json + "</textarea>";
}


来源:https://stackoverflow.com/questions/26670162/different-encoding-of-an-http-request-result-depending-on-the-accept-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!