duanqiang2977 2018-08-15 22:26
浏览 77

将JSON从HTML表单POST到PHP API并在浏览器中下载接收的文件

I have an existing API that only accepts JSON values via a POST, it responds with a downloadable zip file that is only session based, not on a server. I wanted to create an HTML form that could be filled out and POST the JSON values to the API then receive the download. Once the API receives the JSON it will respond with a Zip file that should be downloaded through the browser. I spent a lot of time searching for how to do this and eventually pulled together the components to make it happen. I wanted to share it here because I saw many other people searching for the same thing but with no clear answers or script that worked, lost of GET examples but no POST with in memory server data. In fact may folks said it just couldn't be done with POST.

<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
    $('form').on('submit', function (event) {                           
    //Function montiors for the form submit event
    event.preventDefault(); // Prevents the default action of the form submit button
    var jsonData = '{"PONumber":"' + form1.PONumber.value //JSON data being submitted to the API from the HTML form
            + '","CompanyName":"' + form1.CompanyName.value 
            + '","CompanyID":"' + form1.CompanyID.value 
            + '","ProductName":"' + form1.ProductName.value 
            + '","Quantity":"' + form1.quantity.value 
            + '","Manufacturer":"' + form1.Manufacturer.value + '"}';   

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'api_page.php', true); //The POST to the API page where the JSON will be submitted
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Content-type', 'application/json');       //Additional header fields as necessary
    xhr.setRequestHeader('Authorization', 'Bearer ' + 'eyJ0eXAiOiJKV1QiLCJhbGciO----< SNIP >---547OWZr9ZMEvZBiQpVvU0K0U');
    xhr.onload = function(e) {
        if (this.status == 200) {
            var blob = new Blob([this.response], {type: 'application/zip'});  //We're downloading a Zip file
            var downloadUrl = URL.createObjectURL(blob);
            var a = document.createElement("a");
            a.href = downloadUrl;
            a.download = "download_file.zip"; //The name for the downloaded file that will be saved    
            document.body.appendChild(a);
            a.click();                                              //Automatically starts the download
        } else {
            alert('Unable to download file.')
            }
    };

    xhr.send(jsonData);    //Sends the JSON data to the destination POST page

});

});
</script>
<form method="post" name="form1" id="form1" action="" >
   <td><center><input name="submit" type="submit" value="submit"></center></td>
   <td ><strong>ENTER QUANTITY OF UNITS:  </strong></td><td>&nbsp;</td>
    <td><input name="quantity" type="text" size="17" value="<?php echo $row['value'];?>"></td>
</form>

Here is the code for the PHP server side of the application. The first part is to receive the request.

//Receive the incoming JSON data from the form POST
$jsonRequest = trim(file_get_contents("php://input"));

//Attempt to decode the incoming RAW post data.
$requestDecoded = json_decode($jsonRequest, true);

//Do something with the data and then respond with a zip file.

Here is the PHP code that sends the Zip file back to the original requesting page for download.

$fp = fopen('php://output', 'w');  //Creates output buffer
$mfiles = $yourZipFile   
if($fp && $mfiles) {
     header("Cache-Control: no-cache");
     header("Content-Type: application/zip");
     header("Content-Disposition: attachment; 
                  filename=\"".basename($zipName)."\";");
     header("Content-Transfer-Encoding: binary");
     header("Content-Length: " .strlen($mfiles));
     header("Response-Data: ".$responseData);
     ob_end_clean();
     if (fputs($fp, $mfiles, strlen($mfiles))===FALSE){
         throw new Exception($e);
        }
     }
     else { 
         throw new Exception($e); 
     }
  • 写回答

1条回答 默认 最新

  • doswy02440 2018-08-15 22:26
    关注

    Place the javascript code in the body of your HTML page and it should work just fine. I hope this helps someone else out there in the same position. I've tried to describe each component as best I can and include all of the pieces to make it work.

    Request:  Browser --> HTML form --> JSON --> POST --> PHP
    Response: PHP --> zip file --> Browser Download --> Local PC
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?