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

我该怎么做?


当前回答

imgInp.oncange=evt=>{const[file]=imgInp.fileif(文件){blah.src=URL.createObjectURL(文件)}}<form runat=“server”><input accept=“image/*”type='file'id=“imgInp”/><img id=“blah”src=“#”alt=“your image”/></form>

其他回答

<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>

在React中,如果文件在你的props中,你可以使用:

{props.value instanceof File && (
    <img src={URL.createObjectURL(props.value)}/>
)}

这个解决方案怎么样?

只需将数据属性“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!
}));

见JSFiddle演示

对于我的应用程序,使用加密的GET url参数,只有这一点有效。我总是得到一个TypeError:$(…)为空。摘自https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

函数previewFile(){var preview=document.querySelector('img');var file=document.querySelector('input[type=file]').files[0];var reader=新文件读取器();reader.addEventListener(“load”,函数(){preview.src=读取结果;},假);if(文件){reader.readAsDataURL(文件);}}<input-type=“file”onchange=“previewFile()”><br><img src=“”height=“200”alt=“图像预览…”>

如果您使用React,这里有一个解决方案:

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>
  )
}