【发布时间】:2015-11-10 10:56:31
【问题描述】:
下载 .xlsx 文件时,请求成功,但我的 ajax 错误回调抛出“parsererror - Invalid xml”消息。 我的应用程序从服务器请求一个文件,该服务器是从另一台服务器获取该文件的代理。
在所有三台机器上,我在 .htaccess 中设置了以下内容:
AddType application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx
ajax 调用的结构如下:
var attachment = { name="myfile.xlsx",
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx",
id="resource_id_on_remote-server"}
var path = '/path_to/attachment_file.php?' + $.param(attachment);
$.ajax({
type: "GET",
url: document.getElementById('attachment_download_frame').src = path,
success: function(xhrResponse) {
},
error: function(xhrResponse, errmsg, error) {
//errmsg = "parsererror"
},
complete: function() {
$('#spinner').spin("modal");
}
});
我通过一个隐藏的 iframe 将调用集中起来,该 iframe 实际发起了请求。
服务器文件 attachment_file.php 使用“附件”json 参数从主机服务器请求附件文件:
$id = filter_input(INPUT_GET, 'id');
$contentType = filter_input(INPUT_GET, 'content_type');
$name = filter_input(INPUT_GET, 'name');
$url = REMOTE_BASE_URL . '/api/v1/attachment.json?';
$url .= http_build_query(array('id' => $id, 'name' => $name, 'content_type' => $contentType));
$curl = curl_init($url);
$headers = array(
'Content-Type: ' . $contentType
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTPGET, true);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($response && in_array($httpCode, array(200, 201, 204))) {
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-Type: {$contentType}");
header("Content-Disposition: attachment; filename={$name}");
header("Expires: 0");
header("Pragma: public");
$fh = @fopen('php://output', 'w');
fputs($fh, $response);
} else {
}
请注意如何保留“Content-Type”。我已经验证这确实设置为:“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx”
调用的api服务器是一个Rails应用,使用传入的参数构建文件资源请求:
def fetch_attachment options
url = REMOTE_URL + '/my_attachments/' + options[:id]
response = HTTParty.get(url)
if status? response
return response.parsed_response
else
return false;
end
return false;
end
使用 HTTParty.get 进行请求。在这一刻,我将调查 HTTParty 请求中是否丢失了内容类型。
另外,出于特定原因,我正在从参数中设置 mime 类型。
【问题讨论】:
标签: jquery ajax mime-types