【问题标题】:Spring MVC - setting the content type of a byte[] @ResponseBodySpring MVC - 设置 byte[] @ResponseBody 的内容类型
【发布时间】:2014-10-21 01:03:33
【问题描述】:

我正在使用 Spring MVC 3.2.2.RELEASE,这是我第一次尝试使用 Spring 的基于 Java 的配置 (@Configuration)。

我有一个控制器用于处理某些文件。文件内容由我的服务方法MyContentService.getResource(String)读取。目前,内容类型始终为text/html

如何配置我的 Spring MVC 应用程序,以便它正确设置返回内容的类型?内容类型只能在运行时确定。

我现在的控制器,总是错误地将类型设置为text/html

@Controller
public class MyContentController {

    MyContentService contentService;

    @RequestMapping(value = "content/{contentId}")
    @ResponseBody
    public byte[] index(@PathVariable String contentId) {
        return contentService.getResource(contentId);
    }
}

编辑: 以下方法有效(适用于 PNG 和 JPEG 文件),但我不习惯 URLConnection 确定内容类型(例如 PDF、SWF 等):

@RequestMapping(value = "content/{contentId}/{filename}.{ext}")
public ResponseEntity<byte[]> index2(@PathVariable String contentId, @PathVariable String filename, @PathVariable String ext, HttpServletRequest request) throws IOException {
    byte[] bytes = contentService.getResource(contentId);

    String mimeType = URLConnection.guessContentTypeFromName(filename + "." + ext);
    if (mimeType != null) {
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(mimeType));
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
    } else {
        logger.warn("Unable to determine the mimeType for " + getRequestedUrl(request));
        return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND);
    }
}

【问题讨论】:

  • 返回ResponseEntityHttpEntity 并设置内容类型。
  • 您可以尝试produces 属性,它将响应的Content-Type 标头设置为提供的值,例如:@RequestMapping(value = "content/{contentId}", produces = "application/octet-stream")
  • 您可以将consumesproduces 添加到您的RequestMapping
  • @sp00m & @TJ:设置produces 属性的问题是我不知道所请求的文件类型。它可以是图像、MP4、PDF 等。
  • 您可能想改用javax.activitation.FileTypeMap

标签: java spring spring-mvc web-applications


【解决方案1】:

目前您只返回一个byte[],它不包含太多信息,只返回实际内容(作为byte[])。

您可以将byte[] 包装在HttpEntityResponseEntity 中,并在其上设置适当的内容类型。 Spring MVC 将使用实体的内容类型来设置响应的实际内容类型。

要确定文件类型,您可以使用javax.activation 框架的FileTypeMap 或使用库(请参阅Getting A File's Mime Type In Java)。

@RequestMapping(value = "content/{contentId}")
@ResponseBody
public HttpEntity index(@PathVariable String contentId) {
    String filepath = // get path to file somehow
    String contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(filePath);
    byte[] content = contentService.getResource(contentId);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(mimeType));
    return new HttpEntity(content, headers);
}

【讨论】:

  • @vegemite4me this 帮助你
猜你喜欢
  • 2011-04-06
  • 2015-08-13
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 2011-05-27
  • 2023-03-04
  • 2018-08-05
相关资源
最近更新 更多