【问题标题】:Blueimp File Upload angularjs json prefixBlueimp 文件上传 angularjs json 前缀
【发布时间】:2014-10-21 05:53:39
【问题描述】:

我正在使用 blueimp 文件上传 angularjs 版本,并且大部分都可以正常工作。我遇到的唯一问题是解析 json 响应。

根据 angularjs 团队的建议 - https://docs.angularjs.org/api/ng/service/$http - 所有 application/json 类型的服务器响应都以 ")]}',\n" 为前缀,并且 angularjs 足够聪明,可以剥离它。

我想知道在 blueimp 中我可以在哪里拦截/预处理响应以去除前缀,因为默认情况下它不会发生并导致 json 解析错误。

我有一个 Spring mvc 应用程序,其 MappingJacksonHttpMessageConverter 类处理所有应用程序/json 类型的响应,据我所知,无法禁用特定请求。

提前致谢。

【问题讨论】:

    标签: javascript json angularjs spring blueimp


    【解决方案1】:

    对于遇到相同问题的其他人,我通过在我的 Spring MVC 文件上传控制器类方法中添加一个名为“NoJsonPrefix”的响应头来解决此问题。然后我扩展 Spring MappingJacksonHttpMessageConverter 并检查 NoJsonPrefix 的响应标头。如果存在,则 json 响应没有前缀。这适用于不应该为 json 响应添加前缀的奇怪情况。

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("NoJsonPrefix", "true");
    return new ResponseEntity<Map<String, Object>>(generateResponse(documentDto), responseHeaders, HttpStatus.OK);
    
    public class PrefixedMappingJacksonHttpMessageConverter extends MappingJacksonHttpMessageConverter {
    
    @Value("${http.response.json.prefix}")
    private boolean prefixJson;
    
    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
        JsonGenerator jsonGenerator = getObjectMapper().getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
    
        if (getObjectMapper().getSerializationConfig().isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) {
            jsonGenerator.useDefaultPrettyPrinter();
        }
    
        String noJsonPrefix = outputMessage.getHeaders().getFirst("NoJsonPrefix");
        try {
            if (this.prefixJson && noJsonPrefix == null) {
                jsonGenerator.writeRaw(")]}',\n");
            }
            getObjectMapper().writeValue(jsonGenerator, object);
        } catch (JsonProcessingException ex) {
            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }
    

    }

    <mvc:annotation-driven ignoreDefaultModelOnRedirect="true">
        <mvc:message-converters>
            <bean class="com.***.web.security.PrefixedMappingJacksonHttpMessageConverter">
                <property name="prefixJson" value="${http.response.json.prefix}" />
            </bean>
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
            <bean class="org.springframework.http.converter.FormHttpMessageConverter" />
        </mvc:message-converters>
    </mvc:annotation-driven>
    

    【讨论】:

      猜你喜欢
      • 2014-12-10
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多