首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将JSON从HTML表单发布到PHP API,然后在浏览器中下载接收到的文件

将JSON从HTML表单发布到PHP API,然后在浏览器中下载接收到的文件
EN

Stack Overflow用户
提问于 2018-08-16 06:26:58
回答 1查看 612关注 0票数 0

我有一个现有的API,它只接受通过POST的JSON值,它的响应是一个可下载的zip文件,该文件只基于会话,而不是基于服务器。我想创建一个可以填写的HTML表单,并将JSON值发布到API,然后接收下载。一旦API接收到JSON,它将响应一个Zip文件,该文件应该通过浏览器下载。我花了很多时间研究如何做到这一点,并最终将组件组合在一起,使其成为可能。我之所以想在这里分享它,是因为我看到许多其他人在搜索同样的东西,但没有明确的答案或有效的脚本,丢失了GET示例,但没有POST与内存服务器数据。事实上,人们说这是不能用POST完成的。

代码语言:javascript
复制
<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>

下面是应用程序的PHP服务器端的代码。第一部分是接收请求。

代码语言:javascript
复制
//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.

下面是将Zip文件发送回最初请求下载的页面的PHP代码。

代码语言:javascript
复制
$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); 
     }
EN

回答 1

Stack Overflow用户

发布于 2018-08-16 06:26:58

将javascript代码放在HTML页面的主体中,它就会工作得很好。我希望这对其他处于同样位置的人有所帮助。我已经尽我所能地描述了每个组件,并包含了使其工作的所有部分。

代码语言:javascript
复制
Request:  Browser --> HTML form --> JSON --> POST --> PHP
Response: PHP --> zip file --> Browser Download --> Local PC
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51867284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档