Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在上载图像之前预览图像_Javascript_Jquery_File Upload - Fatal编程技术网

Javascript 在上载图像之前预览图像

Javascript 在上载图像之前预览图像,javascript,jquery,file-upload,Javascript,Jquery,File Upload,我想能够预览一个文件(图像)之前,它是上传。预览操作应该全部在浏览器中执行,而不使用Ajax上载图像 如何执行此操作?请查看下面的示例代码: imgInp.onchange=evt=>{ const[file]=imgInp.files 如果(文件){ blah.src=URL.createObjectURL(文件) } } LeassTaTT的答案在FF和Chrome等“标准”浏览器中运行良好。 IE的解决方案存在,但看起来不同。以下是跨浏览器解决方案的说明: 在HTML中,我们需要两个预览

我想能够预览一个文件(图像)之前,它是上传。预览操作应该全部在浏览器中执行,而不使用Ajax上载图像


如何执行此操作?

请查看下面的示例代码:

imgInp.onchange=evt=>{
const[file]=imgInp.files
如果(文件){
blah.src=URL.createObjectURL(文件)
}
}

LeassTaTT的答案在FF和Chrome等“标准”浏览器中运行良好。 IE的解决方案存在,但看起来不同。以下是跨浏览器解决方案的说明:

在HTML中,我们需要两个预览元素,
img
用于标准浏览器,而
div
用于IE

HTML:

在HTML中,我们包括标准和IE特定的Java脚本:

<script type="text/javascript">
  {% include "pic_preview.js" %}
</script>  
<!--[if gte IE 7]> 
<script type="text/javascript">
  {% include "pic_preview_ie.js" %}
</script>
那是真的。在IE7、IE8、FF和Chrome中工作。请在IE9中测试并报告。 IE预览的想法可以在这里找到:


创建一个加载文件并触发自定义事件的函数怎么样。然后将侦听器附加到输入。这样,我们可以更灵活地使用该文件,而不仅仅是预览图像

/**
 * @param {domElement} input - The input element
 * @param {string} typeData - The type of data to be return in the event object. 
 */
function loadFileFromInput(input,typeData) {
    var reader,
        fileLoadedEvent,
        files = input.files;

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

        reader.onload = function (e) {
            fileLoadedEvent = new CustomEvent('fileLoaded',{
                detail:{
                    data:reader.result,
                    file:files[0]  
                },
                bubbles:true,
                cancelable:true
            });
            input.dispatchEvent(fileLoadedEvent);
        }
        switch(typeData) {
            case 'arraybuffer':
                reader.readAsArrayBuffer(files[0]);
                break;
            case 'dataurl':
                reader.readAsDataURL(files[0]);
                break;
            case 'binarystring':
                reader.readAsBinaryString(files[0]);
                break;
            case 'text':
                reader.readAsText(files[0]);
                break;
        }
    }
}
function fileHandler (e) {
    var data = e.detail.data,
        fileInfo = e.detail.file;

    img.src = data;
}
var input = document.getElementById('inputId'),
    img = document.getElementById('imgId');

input.onchange = function (e) {
    loadFileFromInput(e.target,'dataurl');
};

input.addEventListener('fileLoaded',fileHandler)

也许我的代码不如某些用户好,但我想你会明白这一点的。在这里,您可以看到一个

我已经编辑了@Ivan的答案,以显示“无可用预览”图像,如果它不是图像:

function readURL(input) {
    var url = input.value;
    var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
    if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('.imagepreview').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }else{
         $('.imagepreview').attr('src', '/assets/no_preview.png');
    }
}
对。这是可能的

Html



JS

函数showMyImage(fileInput){
var files=fileInput.files;
对于(var i=0;i
您可以从这里获得。

一行解决方案:

下面的代码使用对象URL,在查看大型图像时比数据URL更高效(数据URL是包含所有文件数据的巨大字符串,而对象URL只是引用内存中文件数据的短字符串):


有几种方法可以做到这一点。最有效的方法是从您的计算机上使用。将此URL传递给,以告知浏览器加载提供的图像

下面是一个例子:


这个解决方案怎么样

只需将数据属性“data type=editable”添加到图像标记中,如下所示:

<img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />

还有你的项目的脚本

function init() {
    $("img[data-type=editable]").each(function (i, e) {
        var _inputFile = $('<input/>')
            .attr('type', 'file')
            .attr('hidden', 'hidden')
            .attr('onchange', 'readImage()')
            .attr('data-image-placeholder', e.id);

        $(e.parentElement).append(_inputFile);

        $(e).on("click", _inputFile, triggerClick);
    });
}

function triggerClick(e) {
    e.data.click();
}

Element.prototype.readImage = function () {
    var _inputFile = this;
    if (_inputFile && _inputFile.files && _inputFile.files[0]) {
        var _fileReader = new FileReader();
        _fileReader.onload = function (e) {
            var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
            var _img = $("#" + _imagePlaceholder);
            _img.attr("src", e.target.result);
        };
        _fileReader.readAsDataURL(_inputFile.files[0]);
    }
};

// 
// IIFE - Immediately Invoked Function Expression
// https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
(

function (yourcode) {
    "use strict";
    // The global jQuery object is passed as a parameter
    yourcode(window.jQuery, window, document);
}(

function ($, window, document) {
    "use strict";
    // The $ is now locally scoped 
    $(function () {
        // The DOM is ready!
        init();
    });

    // The rest of your code goes here!
}));
函数init(){
$(“img[数据类型=可编辑]”)。每个(函数(即,e){
var_inputFile=$('')
.attr('类型','文件')
.attr('隐藏','隐藏')
.attr('onchange','readImage()')
.attr('data-image-placeholder',e.id);
$(e.parentElement).append(\u inputFile);
$(e).on(“单击”,输入文件,触发单击);
});
}
函数触发器单击(e){
e、 数据。单击();
}
Element.prototype.readImage=函数(){
var _inputFile=this;
如果(_inputFile&&_inputFile.files&&&_inputFile.files[0]){
var_fileReader=newfilereader();
_fileReader.onload=函数(e){
var\u imagePlaceholder=\u inputFile.attributes.getNamedItem(“数据图像占位符”).value;
var _img=$(“#”+_imagePlaceholder);
_img.attr(“src”,即target.result);
};
_fileReader.readAsDataURL(_inputFile.files[0]);
}
};
// 
//IIFE-立即调用的函数表达式
// https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
(
函数(代码){
“严格使用”;
//全局jQuery对象作为参数传递
您的代码(window.jQuery、window、document);
}(
函数($、窗口、文档){
“严格使用”;
//$现在是本地作用域
$(函数(){
//DOM准备好了!
init();
});
//剩下的代码在这里!
}));

我制作了一个插件,借助互联网可以在IE7+中产生预览效果,但没有什么限制。我把它放进一个盒子里,这样比较容易拿到

$(函数(){
$(“输入[name=file1]”)。预览图像({
分区:“.预览”,
imgwidth:180,
灯光:120
});
$(“输入[name=file2]”)。预览图像({
分区:“.preview2”,
imgwidth:90,
灯光:90
});
});
.preview>div{
显示:内联块;
文本对齐:居中;
}
.preview2>div{
显示:内联块;
文本对齐:居中;
}

预览
预览2

使用JavaScript(jQuery)和HTML5的多个图像示例

JavaScript(jQuery)

函数readURL(输入){
对于(var i=0;i标记(HTML)


根据伊万·巴耶夫的回答,这里有一个多文件版本

HTML文件

<form id="form1" runat="server">
    <input type="file" id="imgUpload" multiple/>
</form>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>

JavaScript/jQuery

function readURL(input) {
     for(var i =0; i< input.files.length; i++){
         if (input.files[i]) {
            var reader = new FileReader();

            reader.onload = function (e) {
               var img = $('<img id="dynamic">');
               img.attr('src', e.target.result);
               img.appendTo('#form1');  
            }
            reader.readAsDataURL(input.files[i]);
           }
        }
    }

    $("#imgUpload").change(function(){
        readURL(this);
    });
}
$(function() {
    // Multiple images preview in browser
    var imagesPreview = function(input, placeToInsertImagePreview) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                }

                reader.readAsDataURL(input.files[i]);
            }
        }

    };

    $('#gallery-photo-add').on('change', function() {
        imagesPreview(this, 'div.gallery');
    });
});
$(函数(){
//浏览器中的多图像预览
var imagesPreview=函数(输入,放置到插入图像预览){
if(input.files){
var filesamunt=input.files.length;
对于(i=0;ifunction init() {
    $("img[data-type=editable]").each(function (i, e) {
        var _inputFile = $('<input/>')
            .attr('type', 'file')
            .attr('hidden', 'hidden')
            .attr('onchange', 'readImage()')
            .attr('data-image-placeholder', e.id);

        $(e.parentElement).append(_inputFile);

        $(e).on("click", _inputFile, triggerClick);
    });
}

function triggerClick(e) {
    e.data.click();
}

Element.prototype.readImage = function () {
    var _inputFile = this;
    if (_inputFile && _inputFile.files && _inputFile.files[0]) {
        var _fileReader = new FileReader();
        _fileReader.onload = function (e) {
            var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
            var _img = $("#" + _imagePlaceholder);
            _img.attr("src", e.target.result);
        };
        _fileReader.readAsDataURL(_inputFile.files[0]);
    }
};

// 
// IIFE - Immediately Invoked Function Expression
// https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
(

function (yourcode) {
    "use strict";
    // The global jQuery object is passed as a parameter
    yourcode(window.jQuery, window, document);
}(

function ($, window, document) {
    "use strict";
    // The $ is now locally scoped 
    $(function () {
        // The DOM is ready!
        init();
    });

    // The rest of your code goes here!
}));
function readURL(input) {
     for(var i =0; i< input.files.length; i++){
         if (input.files[i]) {
            var reader = new FileReader();

            reader.onload = function (e) {
               var img = $('<img id="dynamic">');
               img.attr('src', e.target.result);
               img.appendTo('#form1');  
            }
            reader.readAsDataURL(input.files[i]);
           }
        }
    }

    $("#imgUpload").change(function(){
        readURL(this);
    });
}
<form id="form1" runat="server">
    <input type="file" id="imgUpload" multiple/>
</form>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
$(function() {
    // Multiple images preview in browser
    var imagesPreview = function(input, placeToInsertImagePreview) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                }

                reader.readAsDataURL(input.files[i]);
            }
        }

    };

    $('#gallery-photo-add').on('change', function() {
        imagesPreview(this, 'div.gallery');
    });
});
<input type='file' onchange="readURL(this);" /> 
<img id="ShowImage" src="#" />
 function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#ShowImage')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }
<img id="image-preview"  style="height:100px; width:100px;"  src="" >

<input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">

<button  onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>


<script type="text/javascript">
function HandleBrowseClick(hidden_input_image)
{
    var fileinputElement = document.getElementById(hidden_input_image);
    fileinputElement.click();
}     
</script>
function assignFilePreviews() {
    $('input[data-previewable=\"true\"]').change(function() {
        var prvCnt = $(this).attr('data-preview-container');
        if (prvCnt) {
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    var img = $('<img>');
                    img.attr('src', e.target.result);
                    img.error(function() {
                        $(prvCnt).html('');
                    });
                    $(prvCnt).html('');
                    img.appendTo(prvCnt);
                }
                reader.readAsDataURL(this.files[0]);
            }
        }
    });
}
$(document).ready(function() {
    assignFilePreviews();
});
<input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
<div class = "prd-img-prv"></div>
function readURL(input) {
    if (input.files && input.files[0]) {
        var i;
        for (i = 0; i < input.files.length; ++i) {
          var reader = new FileReader();
          reader.onload = function (e) {
              $('#form1').append('<img src="'+e.target.result+'">');
          }
          reader.readAsDataURL(input.files[i]);
        }
    }
}
                @Html.TextBoxFor(x => x.productModels.DefaultImage, new {@type = "file", @class = "form-control", onchange = "openFile(event)", @name = "DefaultImage", @id = "DefaultImage" })
                @Html.ValidationMessageFor(model => model.productModels.DefaultImage, "", new { @class = "text-danger" })
                    <img src="~/img/ApHandler.png"  style="height:125px; width:125px" id="DefaultImagePreview"/>
            </div>

 <script>
    var openFile = function (event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function () {
            var dataURL = reader.result;
            var output = document.getElementById('DefaultImagePreview');
            output.src = dataURL;
        };
        reader.readAsDataURL(input.files[0]);
    };
</script>
import * as React from 'react'
import { useDropzone } from 'react-dropzone'

function imageDropper() {
  const [imageUrl, setImageUrl] = React.useState()
  const [imageFile, setImageFile] = React.useState()

  const onDrop = React.useCallback(
    acceptedFiles => {
      const file = acceptedFiles[0]
      setImageFile(file)

      // convert file to data: url
      const reader = new FileReader()
      reader.addEventListener('load', () => setImageUrl(String(reader.result)), false)
      reader.readAsDataURL(file)
    },
    [setImageFile, setImageUrl]
  )
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop })

  return (
    <div>
      <div {...getRootProps()}>
        {imageFile ? imageFile.name : ''}
        {isDragActive ? <p>Drop files here...</p> : <p>Select image file...</p>}
        <input {...getInputProps()} />
      </div>
      {imageUrl && (
        <div>
          Your image: <img src={imageUrl} />
        </div>
      )}
    </div>
  )
}
<input id="ImageMedias" multiple="multiple" name="ImageMedias" type="file"
accept=".jfif,.jpg,.jpeg,.png,.gif" class="custom-file-input"  value="">                                    
<div id="divImageMediaPreview"></div>
$("#ImageMedias").change(function () {
    if (typeof (FileReader) != "undefined") {
        var dvPreview = $("#divImageMediaPreview");
        dvPreview.html("");            
        $($(this)[0].files).each(function () {
            var file = $(this);                
                var reader = new FileReader();
                reader.onload = function (e) {
                    var img = $("<img />");
                    img.attr("style", "width: 150px; height:100px; padding: 10px");
                    img.attr("src", e.target.result);
                    dvPreview.append(img);
                }
                reader.readAsDataURL(file[0]);                
        });
    } else {
        alert("This browser does not support HTML5 FileReader.");
    }
});
{props.value instanceof File && (
    <img src={URL.createObjectURL(props.value)}/>
)}
<img id="blah" alt="your image" width="100" height="100" />
<input type="file" name="photo" id="fileinput" />
<script>
$('#fileinput').change(function() {
var url = window.URL.createObjectURL(this.files[0]);
 $('#blah').attr('src',url);
});
</script>
//profile_change is the id of the input field where we choose an image
document.getElementById("profile_change").addEventListener("change", function() {

//Here we select the first file among the selected files.
const file = this.files[0];

/*here i used a label for the input field which is an image and this image will 
  represent the photo selected and profile_label is the id of this label */
const profile_label = document.getElementById("profile_label");

//Here we check if a file is selected
if(file) {
    //Here we bring in the FileReader which reads the file info. 
    const reader = new FileReader();
    
    /*After reader loads we change the src attribute of the label to the url of the 
    new image selected*/
    reader.addEventListener("load", function() {
        dp_label.setAttribute("src", this.result);
    })

    /*Here we are reading the file as a url i.e, we try to get the location of the 
    file to set that as the src of the label which we did above*/
    reader.readAsDataURL(file);

}else {
    //Here we simply set the src as default, whatever you want if no file is selected.
    dp_label.setAttribute("src", "as_you_want")
}
});
<label for="profile_change">
            <img title="Change Profile Photo" id="profile_label" 
             src="as_you_want" alt="DP" style="height: 150px; width: 150px; 
               border-radius: 50%;" >
</label>
<input style="display: none;" id="profile_change" name="DP" type="file" class="detail form-control">