java - Spring Controller 未返回文件

标签 java spring spring-mvc

我有一个简单的 Spring Controller 设置,用于通过 AJAX 请求返回文件(特别是 .CSV)。这是我正在使用 YUI's 的通话正在制定标准 XHR 的框架:

var downloadFile = Y.all('.downloadLink'); //traverses DOM for all downloadLink <a> tags
    downloadFile.on(
        'click',
        function(e){
            var fileName = e.currentTarget.attr('data-id');//retrieves file name
            Y.io.request(
            '/download/' + fileName, 
            {
                method: 'GET',
                on: {
                    success: function(e) {
                        alert('success');
                    },
                    failure: function(e) {
                        alert(e.type);
                    }
                 }
            });
    }); 

这是我的 Controller :

@RequestMapping( method = RequestMethod.GET, value = "/download/{fileName:.+}")
@ResponseBody
public FileSystemResource download(@PathVariable String fileName) throws IOException {
    File file = new File(rootPath + tempDir + '/' + fileName);
    try {
        if (file.exists()) {
            logger.info(fileName + " downloaded");
            return new FileSystemResource(file); 
        } else {
            logger.error("Could not download: " + fileName + " does not exist on server");
        }
    } catch (Exception e) {
        logger.error("Error Downloading File");
        e.printStackTrace();
    }
    return null;
}

正如本question中所建议的那样,我尝试通过修改方法来强制下载

produces = MediaType.APPLICATION_OCTET_STREAM_VALUE

以及包含 HttpeServletResponse 并使用

设置内容类型
response.setContentType("application/force-download");

在不设置 MediaType 的情况下,我的请求会成功,并且 @ResponseBody 将我的文件内容返回到浏览器。但是,当我包含 MediaType 时,我收到 406:

406 Not Acceptable: The resource identified by this request is only capable 
of generating responses with characteristics not acceptable according to the request "accept" headers.

我已经搜索了文档,但没有找到应该使用哪个“接受”参数来使其成为有效的请求(如果仅此一项就可以解决此问题)。有什么想法或建议的方法来检索我的文件吗?干杯伙伴们,复活节快乐

最佳答案

发出请求时需要设置Accept header 。从未使用过 YUI,但尝试这样的东西

        Y.io.request(
        '/download/' + fileName, 
        {
            method: 'GET',
            on: {
                success: function(e) {
                    alert('success');
                },
                failure: function(e) {
                    alert(e.type);
                }
             }, 
            headers: {'Accept' : 'application/octet-stream'}
        });

关于java - Spring Controller 未返回文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461909/

相关文章:

java - 用于 Spring MVC 3.0 的 JSON 客户端 API

json - 我需要获得 jsonpath 匹配才能使用 Spring mock mvc 的依赖是什么?

SpringMVC - 方法可以返回重定向(字符串)或 ModelAndView

java - 如何在内存中嵌入 MariaDB4j 以替换 JUnit 测试中默认的 Spring DataSource?

spring - 我想获得有关 Spring BeanCreationException 错误的建议

java - 为什么 Spring MVC 4 和 Hystrix 集成在没有 Spring boot API 的情况下无法工作?

java - 使一个类成为 Mockito 模拟而不调用模拟

java - 从 Iterable 创建 List 时使用哪个实现

java - 线程 Java 应用程序

java - 具有相同宽度和高度的Android按钮?