如何限制除jpg png或gif以外的图像大小和扩展名

时间:2019-02-05 04:47:03

标签: javascript jquery html css

我正在使用以下代码在上传之前预览图像,并且效果很好。但是如何解决图片扩展问题,使用户也不会上传任何无效的图片和尺寸

<html lang="en">

<head>

  <title>Change image on select new image from file input</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>

<input type="file" name="file" id="profile-img">
<img src="" id="profile-img-tag" width="200px" />
<br />
<input type="file" name="file" id="profile-img2">
<img src="" id="profile-img2-tag" width="200px" />
<br />
<input type="file" name="file" id="profile-img3">
<img src="" id="profile-img3-tag" width="200px" />


  <script type="text/javascript">
function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#' + $(input).attr('id') + '-tag').attr('src', e.target.result);
    }
    reader.readAsDataURL(input.files[0]);
  }
}

$("[type=file]").change(function() {
  readURL(this);
});
  </script>


</body>

</html>

谢谢。

6 个答案:

答案 0 :(得分:1)

您需要确保图像标签和输入标签都具有不同的id。如果为图像标签赋予与id标签相同的input,但给其后缀-tag,则它将是其自己唯一的id。使用此方法,您可以使用以下行:

$('#'+$(input).attr('id') +'-tag').attr('src', e.target.result);

设置相应图像标签的src属性。

请参见下面的工作示例:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    var extn = input.files[0].type.split('/')[1];
    var size = input.files[0].size;
    var maxSize = 40000; // file must be smaller than 40kb
    
    var valid = ["gif", "png", "jpg", "jpeg"];
    if (valid.includes(extn) && size < maxSize) {
      reader.onload = function(e) {
        $('#' + $(input).attr('id') + '-tag').attr('src', e.target.result);
      }
      reader.readAsDataURL(input.files[0]);
    }
  }
}

$("[type=file]").change(function() {
  readURL(this);
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>

<input type="file" name="file" id="profile-img">
<img src="" id="profile-img-tag" width="200px" />
<br />
<input type="file" name="file" id="profile-img2">
<img src="" id="profile-img2-tag" width="200px" />

答案 1 :(得分:1)

<html lang="en">

<head>

    <title>Change image on select new image from file input</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>

</head>

<style type="text/css">
    .image-holder{
        height: 200px;
    }
    .image-holder img{
      max-height: 100%;
    }
</style>

<body>




<input id="fileUpload_one" type="file" multiple />
<div id="image-holder_one" class="image-holder"></div>



<script type="text/javascript">

$("#fileUpload_one").on('change', function () {

     //Get count of selected files
     var countFiles = $(this)[0].files.length;

     var imgPath = $(this)[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#image-holder_one");
     image_holder.empty();

     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {

             //loop for each file selected for uploaded.
             for (var i = 0; i < countFiles; i++) {

                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumb-image"
                     }).appendTo(image_holder);
                 }

                 image_holder.show();
                 reader.readAsDataURL($(this)[0].files[i]);
             }

         } else {
             alert("This browser does not support FileReader.");
         }
     } else {
         alert("Pls select only images");
     }
 });

</script>





</body>

</html>

将类添加到放置图像的div中,并相应地通过css赋予图像样式。希望对我有帮助。我向div中添加了CSS和类,希望对我有帮助。

答案 2 :(得分:0)

在DOM和您的Javascript代码上,ID必须不同。

function readURL(input, inputId) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
        console.log(input)
            $('#' + inputId + '-tag').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}
$(".profile-img").change(function(){
    readURL(this, this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="file" id="profile-img-1" class="profile-img">

<img src="" id="profile-img-1-tag" width="200px" />

<input type="file" name="file" id="profile-img-2" class="profile-img">

<img src="" id="profile-img-2-tag" width="200px" />

答案 3 :(得分:0)

您可以尝试使用此代码进行多个图像的上传和预览,并且我也在其中添加了验证。

JS代码:

function previewImages() {

  var preview = document.querySelector('#preview');
 
 
  
  if (this.files) {
    [].forEach.call(this.files, readAndPreview);
  }

  function readAndPreview(file) {

  		
  		
  // Make sure `file.name` matches our extensions criteria
    if (!(/\.(jpg|png)$/i.test(file.name)))  {
      return alert(file.name + " is as not image file");
    } 

   else if(file.size/(1024*1024) > 2 ) {
    	 return alert(file.name + " size is greater than 2MB");
    }
    
    var reader = new FileReader();
    
    reader.addEventListener("load", function() {
      var image = new Image();
      image.height = 100;
      image.width = 100;
      image.title  = file.name;
      image.src    = this.result;
      preview.appendChild(image);
    }, false);
    
    reader.readAsDataURL(file);
    
  }

}
document.querySelector('#file-input').addEventListener("change", previewImages, false);
<div class="input-container">
	<div class="multiple-img">
		<p class="choosetext">Choose multiple images :</p>
		<input id="file-input" type="file" id= "files" multiple>
          <div id="preview" ></div>
	</div>

</div>

答案 4 :(得分:0)

打开/删除文件时,您将得到一个文件对象 //删除senario

 c.ondrop = function (e) {
var file=e.dataTransfer.files[0];
       console.log(file.size);//Co,mpare here size
        console.log(this.files[0].type);////Co,mpare type here
            };

输入类型文件senario

document.getElementById(“ inn”)。onchange =函数(e){

        var file =this.files[0];
       console.log(file.size);//Co,mpare here size
         console.log(this.files[0].type);////Co,mpare type here

        fread(this.files[0]);
    };

答案 5 :(得分:0)

这将是最简单的。这都是您的代码。在您的 JavaScript 代码中上传图片时,只需添加所需的const puppeteer = require('puppeteer'); //a list of sites to screenshot const papers = { nytimes: "https://www.nytimes.com/", wapo: "https://www.washingtonpost.com/" }; //launch puppeteer, do everything in .then() handler puppeteer.launch({devtools:false}).then(function(browser){ //create a load_page function that returns a promise which resolves when screenshot is taken async function load_page(paper){ const url = papers[paper]; return new Promise(async function(resolve, reject){ const page = await browser.newPage(); await page.setViewport({width:1024, height: 768}); //screenshot on first console message page.once("console", async console_msg => { await page.pdf({path: paper + '.pdf', printBackground:true, width:'1024px', height:'768px', margin: {top:"0px", right:"0px", bottom:"0px", left:"0px"} }); //close page await page.close(); //resolve promise resolve(); }); //go to page await page.goto(url, {"waitUntil":["load", "networkidle0"]}); }) } //step through the list of papers, calling the above load_page() async function stepThru(){ for(var p in papers){ if(papers.hasOwnProperty(p)){ //wait to load page and screenshot before loading next page await load_page(p); } } //close browser after loop has finished (and all promises resolved) await browser.close(); } //kick it off stepThru(); //getting this error message: //UnhandledPromiseRejectionWarning: Error: Navigation failed because browser has disconnected! }); height属性即可。试试这个:

width
$("#fileUpload_one").on('change', function () {
  //Get count of selected files
  var countFiles = $(this)[0].files.length;
  var imgPath = $(this)[0].value;
  var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
  var image_holder = $("#image-holder_one");
  image_holder.empty();
  if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
    if (typeof (FileReader) != "undefined") {
      //loop for each file selected for uploaded.
      for (var i = 0; i < countFiles; i++) {
        var reader = new FileReader();
        reader.onload = function (e) {
          $("<img />", {
            "src": e.target.result,
            "class": "thumb-image",
            "height": "200px",
            "width": "200px"
          }).appendTo(image_holder);
        }
        image_holder.show();
        reader.readAsDataURL($(this)[0].files[i]);
      }
    } else {
      alert("This browser does not support FileReader.");
    }
  } else {
    alert("Pls select only images");
  }
});