簡體   English   中英

HTML input type=file,提交表單前獲取圖片

[英]HTML input type=file, get the image before submitting the form

我正在構建一個基本的 social.network 並在注冊時用戶上傳顯示圖像。 基本上我想顯示圖像,就像在與表單相同的頁面上預覽一樣,就在他們 select 之后和提交表單之前。

這可能嗎?

以下是在上傳之前預覽圖像的完整示例。

HTML:

<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>

JavaScript:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('#blah')
        .attr('src', e.target.result)
        .width(150)
        .height(200);
    };
    reader.readAsDataURL(input.files[0]);
  }
}

我找到了這個使用fileReader對象的更簡單但功能強大的教程 它只是創建一個img元素,並使用fileReader對象將其source屬性指定為表單輸入的值

 function previewFile() { 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 = ""; } } 
 <input type="file" onchange="previewFile()"><br> <img src="" height="200" alt="Image preview..."> 

這可以通過HTML 5輕松完成,請參閱此鏈接http://www.html5rocks.com/en/tutorials/file/dndfiles/

漂亮的開源文件上傳器

http://blueimp.github.com/jQuery-File-Upload/

我覺得我們之前有過相關的討論: 如何在通過JavaScript上傳之前上傳預覽圖像

圖像在從任何服務器提供之前無法顯示。 因此您需要將圖像上傳到服務器以顯示其預覽。

 const inputImg = document.getElementById('imgInput') const img = document.getElementById('img') function getImg(event){ const file = event.target.files[0]; // 0 = get the first file // console.log(file); let url = window.URL.createObjectURL(file); // console.log(url) img.src = url } inputImg?.addEventListener('change', getImg)
 <img id='img' alt="images"> <input id="imgInput" accept="image/*" type="file">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM