浏览图像并插入Iframe

时间:2014-01-06 21:37:18

标签: javascript html iframe

我想知道这是否可行。

我想创建一个函数来检索图像并插入到iframe中。用户必须能够选择文件(图像/视频),并将其插入到iframe中。

main.html中

<input type="file" id="addImage">我已将此用于用户选择文件。

<iframe class="frame" id="frame" src="insert.html"></iframe>这就是iframe。 iframe src是另一个html文档。

insert.html

<span id="edit"></span>位于需要插入图片的insert.html中。

我不太明白如何使用javascript从用户选择中检索图像并插入iframe。

这可能吗?

2 个答案:

答案 0 :(得分:2)

是的,这是一个例子。关键是挂钩到iframe,然后使用其contentWindow

<强> EDIT

此外,我不知道你是否意味着浏览文件或拖放API,所以我实现了两者。

来自这些来源的大量帮助:

这是一个小提琴:

JSFiddle

<强> CSS

 *{
    font-family: Arial;
 }
 .section{
    width: 400px;
    padding: 20px;
    margin: auto;
 }
 #dragDiv{
    background-color: #ffffcc;
 }
 #browseDiv{
    background-color: #ccffcc;
 }
 #iframeDiv{
    background-color: #ffcccc;
 }
 #dropTarget{
    width: 300px;
    height: 300px;
    border-style: dashed;
    border-width: 5px;
 }
 .dropEnabled{
    border-color: #999999;
 }
 .dropEnabled:hover{
    border-color: #ff9933;
 }
 .dropMe{
    border-color: #99ff99;
 }

<强> JS

 /**
  * I set up the listeners for dragging and dropping as well
  * as creating an iFrame for holding dragged in images
  * @returns {undefined}
  */
 function main() {
    // The div that receives drops and the new iFrame
    var targetDiv = document.getElementById("dropTarget"),
            iframe = document.createElement("iframe");

    // Set the iframe to a blank page
    iframe.src = "about:blank";

    // Append it to the target
    document.getElementById("iframeTarget").appendChild(iframe);

    // Drag over is when an object is hovering over the div
    // e.preventDefault keeps the page from changing
    targetDiv.addEventListener("dragover", function(e) {
       e.preventDefault();
       this.className = "dropMe";
    }, false);

    // Drag leave is when the object leaves the div but isn't dropped
    targetDiv.addEventListener("dragleave", function(e) {
       e.preventDefault();
       this.className = "dropEnabled";
    }, false);

    // Drop is when the click is released
    targetDiv.addEventListener("drop", function(e) {
       e.preventDefault();
       this.className = "dropEnabled";
       loadFile(e.dataTransfer.files[0], iframe);
    }, false);

    document.getElementById("upload").addEventListener("click", function() {
       var file = document.getElementById("browsedFile").files[0];
       loadFile(file, iframe);
    }, false);
 }

 /**
  * Load a file and then put it on an ifrmae
  * @param {Element} f The file that needs to get loaded
  * @param {Element} destination The iframe that the file is appended to
  * @returns {undefined}
  */
 function loadFile(f, destination) {
    // Make a file reader to interpret the file
    var reader = new FileReader();

    // When the reader is done reading,
    // Make a new image tag and append it to the iFrame
    reader.onload = function(event) {
       var newImage = document.createElement("img");
       newImage.src = event.target.result;
       destination.contentWindow.document.getElementsByTagName("body")[0].appendChild(newImage);
    };

    // Tell the reader to start reading asynchrounously
    reader.readAsDataURL(f);
 }

 // Run the main script
 window.onload = main;

<强> HTML

<!DOCTYPE html>
<html>
   <head>
      <title>I framed it</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
   </head>
   <body>
      <div id="dragDiv" class="section">
         <div>The div below receives dragged in files</div>
         <div id="dropTarget" class="dropEnabled"></div>
      </div>
      <div id="browseDiv" class="section">
         <div>I upload stuff the boring way</div>
         <input type="file" id="browsedFile"><button id="upload">Upload</button>
      </div>
      <div id="iframeDiv" class="section">
         <div>And below me, an iFrame gets created</div>
         <div id="iframeTarget"></div>
      </div>
   </body>
</html>

结果如下:

enter image description here

DOM:

enter image description here

<强> EDIT

关于如何使用视频进行评论。有几种方法可以做到这一点,但这是我使用HTML5 <vido>标记执行此操作的一种方法,您可以在此处找到更多相关信息:HTML Videos

我敢肯定的一个棘手的事情是如何说明你应该加载什么样的文件。我在文件的switch()属性上使用type,对于MP4视频,该属性通常会评估为:image/pngvideo/mp4。但是,这会将您绑定到特定的文件格式。 更好的方法是制作一个正则表达式,以确定它是只是图像或视频,并忽略格式,因为该过程 rougly 对于这些类型的所有文件都是一样的。

我添加了自己的正则表达式实现。可能不是最好的,但它允许所有适当的图像类型现在通过。

另外,我尝试使用Apple的一些示例视频,可在此处找到:Sample QuickTime Movies。但是,那些因某些原因无效。所以在那之后,我刚刚下载了W3Schools在他们的教程中使用的示例视频。我告诉你这个,如果你尝试它并且它不起作用,它可能是文件本身而不是你的代码。

已编辑loadFile()功能

 /**
  * Load a file and then put it on an ifrmae
  * @param {Element} f The file that needs to get loaded
  * @param {Element} destination The iframe that the file is appended to
  * @returns {undefined}
  */
 function loadFile(f, destination) {
    // Make a file reader to interpret the file
    var reader = new FileReader(),
            loaderFunc = null,
            typeRegEx = /^(\w+)\//,
            contentType = f.type.match(typeRegEx)[1];

    // Figure out how to load the data
    switch (contentType) {
       case "video":
          loaderFunc = function(event) {
             var newVideo = document.createElement("video"),
                     newVideoSource = document.createElement("source");

             newVideo.width = 300;
             newVideo.height = 300;
             newVideo.setAttribute("controls");

             newVideoSource.src = event.target.result;
             newVideoSource.type = f.type;

             destination.contentWindow.document.getElementsByTagName("body")[0].appendChild(newVideo);
             newVideo.appendChild(newVideoSource);
          };
          break;
       case "image":
          loaderFunc = function(event) {
             var newImage = document.createElement("img");
             newImage.src = event.target.result;
             destination.contentWindow.document.getElementsByTagName("body")[0].appendChild(newImage);
          };
          break;
       default:
          console.log("Unknown file type");
          return;
    }

    // We should have returned, but just make sure
    if (loaderFunc) {
       // When the reader is done reading,
       // Make a new image tag and append it to the iFrame
       reader.onload = loaderFunc;

       // Tell the reader to start reading asynchrounously
       reader.readAsDataURL(f);
    }
 }

答案 1 :(得分:0)

如果iframe来自同一个网域,您可以直接操纵iframe。

请参阅jQuery/JavaScript: accessing contents of an iframe

如果不是这样,你可以做的是:

在两个页面之间设置通信流程(请参阅How to communicate between iframe and the parent site?

将文件上传到服务器,然后刷新“insert.html”页面以显示上传的图像。

相关问题