相关疑难解决方法(0)

使用Spring MVC的ResponseEntity返回一个流

我有一个Spring MVC方法返回一个ResponseEntity.根据检索到的特定数据,有时需要将数据流返回给用户.其他时候它会返回除流之外的其他内容,有时还会返回重定向.我绝对希望这是一个流而不是字节数组,因为它可能很大.

目前,我使用以下代码段返回流:

HttpHeaders httpHeaders = createHttpHeaders();
IOUtils.copy(inputStream, httpServletResponse.getOutputStream());

return new ResponseEntity(httpHeaders, HttpStatus.OK);
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不允许Spring HttpHeaders数据实际填充响应中的HTTP标头.这是有道理的,因为我的代码写入OutputStreamSpring之前收到的ResponseEntity.

这将是非常好的以某种方式返回一个ResponseEntity带有InputStream一个让Spring处理.它也会与我的函数的其他路径并行,我可以成功返回一个ResponseEntity.无论如何,我可以用Spring完成这个任务吗?


此外,我也尝试返回InputStreamResponseEntity只是为了看看春天会接受它.

return new ResponseEntity(inputStream, httpHeaders, HttpStatus.OK);
Run Code Online (Sandbox Code Playgroud)

但它抛出了这个异常:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
Run Code Online (Sandbox Code Playgroud)

我可以通过HttpServletResponse直接设置所有内容来使我的功能工作,但我想只用Spring做到这一点.

java spring servlets spring-mvc

44
推荐指数
1
解决办法
5万
查看次数

从具有OutputStream的Spring @Controller返回文件

我想从Spring控制器返回一个文件.我已经有API可以给我任何OutputStream的实现,然后我需要将它发送给用户.

所以流程是这样的:

获取输出流- >服务将此输出流传递给控制器- >控制器必须将其发送给用户

我想我需要输入流来做这件事,我也发现了Apache Commons api功能,如下所示:

IOUtils.copy(InputStream is, OutputStream os)
Run Code Online (Sandbox Code Playgroud)

但问题是,它将它转换到另一边 - >不是从osis,而是从isos.

编辑

要清楚,因为我看到答案没有正确的事情:
我使用Dropbox api并在OutputStream中接收文件,我希望在输入一些URL时将此输出流发送给用户

FileOutputStream outputStream = new FileOutputStream(); //can be any instance of OutputStream
DbxEntry.File downloadedFile = client.getFile("/fileName.mp3", null, outputStream);
Run Code Online (Sandbox Code Playgroud)

这就是为什么我在谈论将输出转换为输入,但不知道如何做到这一点.此外,我认为有更好的方法来解决这个问题(可能从输出流以某种方式返回字节数组)

我试图通过参数将servlet outputstream [response.getOutputstream()]传递给从dropbox下载文件的方法,但它根本没用

编辑2

(我不能以优雅的形式粘贴代码,不知道为什么,所以我将使用代码粘贴pastebin.com链接)

我的应用程序的"流程"是这样的:@Joeblade

  1. 用户输入url:/ download/{file_name}

  2. Spring Controller捕获url并调用@Service层下载文件并将其传递给该控制器:http://pastebin.com/dW6zkGWT

  3. 现在@Service调用Dropbox API并按指定的file_name下载文件,并将其全部放到OutputStream中,然后传递它(以某种形式......可能是OutputStream,byte []数组或任何其他对象 - 我不知道哪个是更好地使用)到控制器:http …

java spring file spring-mvc

11
推荐指数
4
解决办法
7万
查看次数

如何在Spring中从Web服务发送图像

使用Spring Web Service发送图像时遇到问题.

我写了如下控制器

@Controller
public class WebService {

    @RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET)
    public @ResponseBody byte[] getImage() {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg");
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write( bufferedImage  , "jpg", byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

@ResponseBody 将响应转换为JSON.

我正在使用RestClient来测试Web服务.

但是当我点击http://localhost:8080/my-war-name/rest/imageURL时.

Header 
Accept=image/jpg
Run Code Online (Sandbox Code Playgroud)

我在RestClient上面临以下错误

使用windows-1252编码将响应正文转换为字符串失败.响应机构未设置!

当我使用浏览器Chrome和Firefox时

标题没有添加,所以错误是预期的(请指导我这个)

HTTP Status 405 - Request method 'GET' not supported …

java spring json spring-mvc

10
推荐指数
3
解决办法
4万
查看次数

如何将Spring REST中的图像返回到浏览器

我需要在Spring控制器中返回图像.我在这个Spring MVC中尝试回答:如何在@ResponseBody中返回图像?但它不起作用

我的代码是这样的

@RequestMapping(value = "cabang/photo", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> getPhoto() throws IOException {

     File imgPath = new File("D:\\test.jpg");

    byte[] image = Files.readAllBytes(imgPath.toPath());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    headers.setContentLength(image.length);
    return new ResponseEntity<>(image, headers, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

但是当我在浏览器中访问它时,它没有显示任何内容(只是没有图片图标).但是如果我读取图像字节数组,它就不是空的.我的代码中是否有任何遗漏?

rest spring controller image spring-rest

6
推荐指数
1
解决办法
4717
查看次数

什么是使用Spring MVC流媒体的正确方法

我有一个控制器方法,简单地将媒体(图像,css,js等)的字节流传输到客户端.我首先尝试过这样的事情:

@RequestMapping(value="/path/to/media/**", method=RequestMethod.GET)
@ResponseBody
public byte[] getMedia(HttpServletRequest request) throws IOException
{
    //logic for getting path to media on server

    return Files.readAllBytes(Paths.get(serverPathToMedia));
}
Run Code Online (Sandbox Code Playgroud)

我最初在Firefox中对此进行了测试,看起来一切正常.但是,我在Chrome中尝试了它,然后发现没有任何图像有效.所以,我然后把它改成这样的东西:

@RequestMapping(value="/path/to/media/**", method=RequestMethod.GET)
public ResponseEntity<byte[]> getMedia(HttpServletRequest request) throws IOException
{
    //logic for getting path to media on server

    byte[] bytes = Files.readAllBytes(Paths.get(serverPathToMedia));
    //logic for setting some header values like Content-Type and Content-Length
    return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

这给出了与以前相同的结果.我在开发人员工具中看到我的响应标头按预期下降,但仍然没有图像字节

接下来我尝试了这样的事情:

@RequestMapping(value="/path/to/media/**", method=RequestMethod.GET)
public void getMedia(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    //logic for getting path to media on …
Run Code Online (Sandbox Code Playgroud)

java controller spring-mvc

5
推荐指数
1
解决办法
7880
查看次数

Spring MVC:如何从控制器返回图像?

我正在尝试返回这样的图像。

 @RequestMapping(value = "admin/image/{userId}")
public ResponseEntity<byte[]> getPhoto(@PathVariable int userId) throws IOException {
    UserDB userDB = UserDBService.getUserWithId(userId);
    if (userDB != null) {
        try {
            byte[] image;
            try {
                String path = ApplicationPropertiesConstants.SAFESITE_DOCUMENTS_DIRECTORY + userDB.getSite().getId() + "\\342.png";
                InputStream is = new FileInputStream(path);
                BufferedImage img = ImageIO.read(is);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ImageIO.write(img, "png", bos);
                final HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.IMAGE_PNG);

                return new ResponseEntity<byte[]>(IOUtils.toByteArray(is), headers, HttpStatus.CREATED);
            } catch (FileNotFoundException e) {
                image = org.apache.commons.io.FileUtils.readFileToByteArray(new File("dfd"));
            }

            return null;
        } catch (IOException ignored) …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc

5
推荐指数
1
解决办法
2万
查看次数

如何将Image作为ResponseEntity <byte []>返回并使用Thyme leaf显示相同内容

我正在使用百里香叶作为我的项目,我在生成QRCode时遇到问题,并在浏览器中显示相同的问题,我正在使用spring mvc框架.

  1. 我将产品ID发送到API层,该层必须为该ID创建QR码.这不应该保存在任何地方并作为响应返回byte []
  2. 使用百里香叶框架必须在浏览器中显示图像

请帮忙.

关心莫汉

java spring-mvc thymeleaf

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

spring-mvc ×6

java ×5

spring ×5

controller ×2

file ×1

image ×1

json ×1

rest ×1

servlets ×1

spring-rest ×1

thymeleaf ×1