简体   繁体   English

使用发布请求下载Excel文件

[英]download excel file using post request

I've an API endpoint that takes in a JSON and returns a excel file. 我有一个接受JSON并返回excel文件的API端点。 The endpoint directly sends the file, not the link to the file. 端点直接发送文件,而不是文件的链接。 How do I download the file using JQuery AJAX. 如何使用JQuery AJAX下载文件。

Backend Code: 后端代码:

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']);
}

Frontend Code: 前端代码:

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;
  });
});

I don't want to save the file in server beforehand, but just download it. 我不想事先将文件保存在服务器中,而只是下载它。 Thanks in advance. 提前致谢。

The problem in the above question was, I was able to download the file but it was corrupted. 上面问题中的问题是,我能够下载文件,但文件已损坏。 I fixed it by setting responseType of xhr to blob . 我通过将xhr的responseType设置为blob来修复它。

New AJAX code for reference: 新的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM