【问题标题】:Dynamically uploading images in HTML and Javascript以 HTML 和 Javascript 动态上传图像
【发布时间】:2015-03-25 01:02:56
【问题描述】:

如何使用 HTML 和 Javascript 上传多个单独的图像?我拥有的代码基于此https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL,但我希望可以选择创建多个上传按钮,并且每个上传按钮都应该上传独立于其他按钮的单个图像。 这是我的代码:

<!DOCTYPE html>

     <a class="btn btn-default" href="#" role="button" onclick = "addEntry()" >Add</a>
      <script>
            function addEntry() {
            var browse = document.createElement("INPUT");
            browse.setAttribute("type", "file");

            picture = document.createElement("img");
            picture.src = "";
            picture.setAttribute("alt", "No image chosen");
            picture.setAttribute("height","100");
            browse.setAttribute("onchange", "previewFile(picture)");
            document.body.appendChild(browse);
            document.body.appendChild(picture);
            }

            function previewFile(inPic){

            var preview = document.querySelector('img');
            var file    = document.querySelector('input[type=file]').files[0]; 
            var reader  = new FileReader();


            reader.onloadend = function () {
                preview.src = reader.result;
            }

            if (file) {
                reader.readAsDataURL(file); 
            } else {
                preview.src = "";
            }
            }

【问题讨论】:

  • 这段代码的具体问题是什么?
  • 我认为这与 querySelector 部分有关。基本上,当我使用第一个上传按钮时,它会上传并显示图像。当我使用任何其他按钮上传时,文件会上传但没有图像出现。
  • 视觉参考:jsfiddle.net/3jdL8nu7

标签: javascript html image file upload


【解决方案1】:

无需使用文件阅读器。

如果您不必支持古代浏览器,请使用FormData

从那里编码 sn-p:

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"

// HTML file input user's choice...
formData.append("userfile", fileInputElement.files[0]);

// JavaScript file-like object...
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2015-10-21
    • 2019-09-17
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多