我有一个服务器使用Java的Spring库,当我在客户端执行AJAX帖子时,它会根据参数 queryParam 生成一个.csv文件。
$.ajax(
{
url: myUrl,
type: 'POST',
contentType: 'application/json',
data: queryParam,
success: function(response)
{
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.error("error in query()");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
服务器端代码附加相应的标头并将数据直接写入响应流(请注意我必须这样做,因为我无法在服务器上创建文件):
@RequestMapping(value = "/query", method = RequestMethod.POST)
public void exportSearchEvents(HttpServletResponse resp, @RequestBody QueryParams params)
{
Writer os=null;
try
{
resp.setHeader("Content-Disposition", "attachment; filename=\"searchresults.csv\"");
resp.addHeader("Content-Type", "application/force-download");
resp.addHeader("Content-Type", "application/csv");
resp.addHeader("Content-Type", "application/x-download");
resp.setContentLength(580);
resp.addHeader("Pragma", "public");
resp.addHeader("Expires", "0");
resp.addHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
os = resp.getWriter();
createFile(os, params); //writes the .csv data to the response PrintWriter object
os.flush();
os.close();
}
catch(Exception e)
{
logger.info("Error creating .csv file. " + e.getMessage());
logger.error("Error creating .csv file.", e);
}
logger.info("got to here. " + resp.toString());
if(os==null)
{
logger.info("Error creating .csv file: null");
logger.error("Error creating .csv file: null");
return;
}
return;
}
当它返回时,我得到结果的字符串(应该在.csv中),但是不会弹出下载选项框。
另外,我应该提一下,我不能在服务器上创建文件并链接到它(即 document.location.href = /server/createdfile.csv 或由于无法更改的文件权限,从浏览器中获取。而且我也尝试了各种形式的隐藏iframe,它们可以反映到各个地方,但由于我必须以某种方式将 queryParam 提供给服务器,我不能这样做(如果我错了,请纠正我) 。
由于Spring的局限性,简单的POST和GET不起作用(我假设它是Spring的一个问题):
$.get(myUrl, queryParam, function(response)
{
console.log(response);
});
和
$.post(myUrl, queryParam, function(response)
{
console.log(response);
});
告诉我:
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().
另请注意,我正在避免使用Flash,所以请不要回答Flash。
提前致谢。
答案 0 :(得分:0)
http://gloryplus.com/index.php?route=product/product&path=81&product_id=283
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}