Show files in new window

谁说我不能喝 提交于 2021-01-28 13:50:38

问题


I want to display or show my file in a new tab, but before that, I had to upload my file first

I've tried to use FileReader() and I can't load the image

function readURL(input) {

  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#blah').attr('src', e.target.result);
      window.open(e.target.result);
    }

    reader.readAsDataURL(input.files[0]);

  }
}

$("#imgInp").change(function() {
  readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1" runat="server">
  <input type='file' id="imgInp" />
  <img id="blah" src="#" alt="your image" />
</form>


回答1:


You can't open it directly using "data:...." as url, but you can save that image in local storage and use it on another page

<!-- FIRST PAGE -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Page Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    </head>
    <body>
        <form id="form1" runat="server">
            <input type='file' id="imgInp" />
            <img id="blah" src="#" alt="your image" />
        </form>
        <script>
        function readURL(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    $('#blah').attr('src', e.target.result);
                    window.open("second_page.html", "_blank");
                    localStorage.setItem("image",e.target.result);
                }

                reader.readAsDataURL(input.files[0]);

            }
        }

        $("#imgInp").change(function() {
            readURL(this);
        });
        </script>
    </body>
</html>
<!--SECOND PAGE -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
    <img id="img2" src="#" alt="your image" />
</body>
</html>
<script>
$(document).ready(function() {
    $("#img2").attr('src', localStorage.getItem("image"));
});
</script>


来源:https://stackoverflow.com/questions/55276608/show-files-in-new-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!