gpt4 book ai didi

java - Spring Controller 未返回文件

转载 作者:行者123 更新时间:2023-12-02 04:48:36 25 4
gpt4 key购买 nike

我有一个简单的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com