通过Spring Boot控制器发送文件列表

时间:2016-07-13 15:05:25

标签: spring spring-boot

我有以下控制器:

 @RequestMapping(value = "/url", method = RequestMethod.GET)
        public List<ResponseEntity<InputStreamResource>> getLayouts(@RequestParam("app") String app, HttpServletResponse response) {
.....
                inputStreamResource = new InputStreamResource(new FileInputStream(file));               
                HttpHeaders responseHeaders = new HttpHeaders();
                responseHeaders.set(HttpHeaders.CONTENT_TYPE, "application/xml");
                responseHeaders.setContentLength(file.length());
                responseHeaders.add(HttpHeaders.CONTENT_ENCODING, "UTF-8");
                ResponseEntity inputStreams = new ResponseEntity(inputStreamResource, responseHeaders, HttpStatus.OK);
                inputStreamResources.add(inputStreams);
.....
        }

所以问题是它不起作用。首先我遇到了问题:

No serializer found for class java.io.FileDescriptor 
and no properties discovered to create BeanSerializer 
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

然后我补充道:

objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

问题消失了,但出现了新问题:我看到我的inputStream重复了很多次,现在我有一个错误:

 at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:693) ~[jackson-databind-2.6.5.jar:2.6.5]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:675) ~[jackson-databind-2.6.5.jar:2.6.5]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157) ~[jackson-databind-2.6.5.jar:2.6.5]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:693) ~[jackson-databind-2.6.5.jar:2.6.5]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:675) ~[jackson-databind-2.6.5.jar:2.6.5]

我的问题我做错了什么或错过了什么?有没有更好的方法来发送文件列表,也许我的方法一般是错的?

1 个答案:

答案 0 :(得分:1)

取决于您想要做什么,如果您想要返回路径和内容,那么我会返回类似public class FileResource { private String fileName; private byte[] content; // getters, setters } 的内容,其中<animated-vector android:drawable="@drawable/ic_play" xmlns:android="http://schemas.android.com/apk/res/android" > <target android:animation="@animator/play_to_pause" android:name="play"/> </animated-vector> 将是您自己的类:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="240.0dp"
    android:height="240.0dp"
    android:viewportHeight="24.0"
    android:viewportWidth="24.0">
    <path
        android:name="play"
        android:fillColor="@color/colorPrimary"
        android:pathData="M 11 10 L 17 10 L 17 26 L 11 26 M 20 10 L 26 10 L 26 26 L 20 26" />
</vector>

但请注意,虽然这种方法可能会消耗大量内存并导致巨大的响应 - 对于较大的文件,您可能只想返回文件名列表,然后让客户端逐个请求文件,于是您将文件内容直接流式传输到输出。或者您可以将文件压缩到单个存档中并将存档返回给客户端(就像许多云存储一样)。

您可能还想查看https://spring.io/guides/gs/uploading-files/