Mar*_*ope 4 java spring spring-mvc
我有一个提供文件(图像,PDF等的控制器):
@Controller
public class FileController {
@ResponseBody
@RequestMapping("/{filename}")
public Object download(@PathVariable String filename) throws Exception {
returns MyFile.findFile(filename);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我请求带有以下Accept标头的文件,则会得到406:
Run Code Online (Sandbox Code Playgroud)Request URL: http://localhost:8080/files/thmb_AA039258_204255d0.png Request Method:GET Status Code:406 Not Acceptable Request Headers Accept:*/*
如果我请求带有以下Accept标头的文件,则得到200:
Run Code Online (Sandbox Code Playgroud)URL: http://localhost:8080/files/thmb_AA039258_204255d0.png Request Method: GET Status Code:200 OK Request Headers Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
这是我的spring-mvc上下文中的唯一视图解析器:
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
无论如何,有没有配置spring mvc忽略Accept标头?我已经看到了使用ContentNegotiatingViewResolver进行此操作的示例,但仅用于处理xml和json。
所以这是我最终得到的代码,以使其正常工作:
@Controller
public class FileController {
@ResponseBody
@RequestMapping("/{filename}")
public void download(@PathVariable String filename, ServletResponse response) throws Exception {
MyFile file = MyFile.find(filename);
response.setContentType(file.getContentType());
response.getOutputStream().write(file.getBytes());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5476 次 |
| 最近记录: |