我有一个API端点,它接受一个JSON并返回一个excel文件。端点直接发送文件,而不是文件的链接。如何使用JQuery AJAX下载文件。
后端代码:
public function postExcel() {
// Parse request body
$reqBody = json_decode(file_get_contents('php://input'));
// On Valid Request
if(isset($reqBody, $reqBody->regno, $reqBody->offset) && $reqBody->offset < 100 && $reqBody->offset >= 0) {
// Create and add metadata to the workbook
$workbook = new \PHPExcel();
$workbook->getProperties()
->setCreator('AUScraper')
->setTitle('AU Results')
->setLastModifiedBy('AUScraper')
->setDescription('generated by AUScraper')
->setSubject('generated by AUScraper')
->setKeywords('anna university unofficial semester result API')
->setCategory('semester results');
$worksheet = $workbook->getSheet(0);
$worksheet->setTitle('results');
// Get the results
$results = $this->requestAU($reqBody->regno, $reqBody->offset);
// Update worksheet
//Output the file
ob_clean();
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=\"results.xlsx\"");
header("Cache-Control: max-age=0");
header("Expires: 0");
$workbookWriter = new \PHPExcel_Writer_Excel2007($workbook);
$workbookWriter->save("php://output");
}
// On Invalid Request
header('Content-Type: application/json');
http_response_code(400);
return json_encode(['error' => 'invalid request']);
}
前端代码:
import $ from 'jquery';
import 'materialize';
$(() => {
$('#reg_form').submit(() => {
// format data to send
let form_data = {};
form_data.regno = $('#reg_no').val();
form_data.offset = $('#offset').val();
// Send the request
$.ajax({
url: 'http://localhost/git_repo/AUScraper/app/public/api/excel',
data: JSON.stringify(form_data),
type: 'POST',
contentType: 'application/json',
success: function(data) {
var blob=new Blob([data], {type : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="result_"+new Date()+".xlsx";
link.click();
},
error: (xhr,status,error) => {
let errorMessage = JSON.parse(xhr.responseText);
Materialize.toast(errorMessage.error, 2000);
}
});
return false;
});
});
我不想事先将文件保存在服务器中,而只是下载它。提前谢谢。
答案 0 :(得分:0)
上述问题的问题是,我能够下载该文件,但它已损坏。我通过将responseType
xhr设置为blob
来修复它。
新的AJAX代码供参考:
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/git_repo/AUScraper/app/public/api/excel');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
let link=document.createElement('a');
link.href=window.URL.createObjectURL(this.response);
link.download="results.xlsx";
link.click();
}
else {
Materialize.toast('Invalid data!', 2000);
}
}
xhr.send(form_data);