简体   繁体   English

AJAX 上传动态创建的 HTML 文件

[英]AJAX upload dynamically created HTML file

I have a webpage that allows drop down elements to dynamically create HTML.我有一个允许下拉元素动态创建 HTML 的网页。 On this page I also have a "create File" button.在此页面上,我还有一个“创建文件”按钮。 When I click this button, I want it to make an AJAX POST request and upload this dynamic page I created with drag and drops to be uploaded as a File.当我单击此按钮时,我希望它发出 AJAX POST 请求并上传我通过拖放创建的动态页面以作为文件上传。

Here is a simple HTML file to visualize how the file will look like:这是一个简单的 HTML 文件,用于可视化文件的外观:

<!doctype html>
<html>

<head>
  <title>Test Drag and Drop</title>
</head> 

<body>
     <div class="dynamicPage">

          <div class="subSections">
          </div>

          <div class="subSections">
          </div>

           <!-- more elements and objects in here -->
     </div>

     <div class="stripFromPage">

          <!-- More buttons for drag and drop elements to main page -->
         <button onclick="createFile(this)">Create File</button>
     </div>
</body>

 <script>

   function createFile(elem){

   let url = "action/saveFile";

   var formData = new FormData();

   formData.append('filename', 'test.html');
   formData.append('file', $("html").html());


   $.ajax({
      type: 'POST',
      url: url,
      data: formData,
      contentType: false,
      processData: false,
      success: function (data) {
      alert(data);
      }
   });

  }


 </script>

On the server side I have node.js with a upload method that works for IOS app using the form method, so I know that part is good.在服务器端,我有一个带有上传方法的 node.js,该方法适用于使用 form 方法的 IOS 应用程序,所以我知道这部分很好。

The part I need help with is how to upload DOM object as file and append it to form correctly, specify the name of this file so the backend can save it as that filename.我需要帮助的部分是如何将 DOM 对象作为文件上传并将其附加到正确的表单中,指定此文件的名称以便后端可以将其保存为该文件名。

I prefer javascript over jquery.我更喜欢 javascript 而不是 jquery。 But I couldn't find any good javascript code for AJAX file upload, so I have jquery here.但是我找不到任何用于 AJAX 文件上传的好的 javascript 代码,所以我在这里有 jquery。

You could create a Blob object with the HTML string and send it to the server (untested).您可以使用 HTML 字符串创建一个 Blob 对象并将其发送到服务器(未经测试)。

var formData = new FormData();
formData.append('filename', 'test.html');
var dynamicPage = $(elem).html(); // the body of the new file...
var fileBlob = new Blob([dynamicPage], { type: "text/html"});
formData.append('file', fileBlob);

Or these two links may help you: Creating Javascript Blob() with data from HTML Element.或者这两个链接可能对您有所帮助: 使用 HTML 元素中的数据创建 Javascript Blob()。 Then downloading it as a text file 然后将其下载为文本文件

https://javascript.info/blob https://javascript.info/blob

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

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