java - 下载时如何设置文件类型?

标签 java spring spring-boot

我有一个返回文件的 Spring 端点:

@RequestMapping(value = "/files/{merchant_id}", method = RequestMethod.GET)
    public void getFile(@PathVariable("merchant_id") Integer merchant_id, HttpServletResponse response) {

        try {
          File initialFile = new File("/opt/1/Why_Brookfield_Callout_3x.png");
          InputStream is = FileUtils.openInputStream(initialFile);
          org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
          response.flushBuffer();
        } catch (IOException ex) {
          throw new RuntimeException("IOError writing file to output stream");
        }
    }

但是当我下载文件时,我得到了输入文本。 如何将文件的类型设置为 .png 文件?

最佳答案

在您的@RequestMapping中添加products = MediaType.IMAGE_PNG

参见https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/MediaType.html更多媒体类型

因此方法定义变为:

@RequestMapping(value = "/files/{merchant_id}", method = RequestMethod.GET, produces = org.springframework.http.MediaType.IMAGE_PNG)

关于java - 下载时如何设置文件类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57547682/

相关文章:

java - 将 @EJB 注入(inject)显式创建的对象 -> NullPointerException

java - 在 JPanel 之间绘图

java - 在字符串中查找 CRLF

java - 为柑橘环境变量分配特定值后是否可以更改它们

java - Spring Boot jpa接口(interface)-进行自定义查询

java - 如何在android中的文件中包含字符串数组中的路径

java - Spring Boot 数据 - 未找到属性注册

java - 在Tomcat下开发GWT?

spring-boot - 使用 spring boot Jersey starter 部署为 WAR 时的映射冲突

java - Spring boot webjars未生成,Http 406返回