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

我该怎么做?


当前回答

用于多图像上传(对@IvanBaev解决方案的修改)

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

http://jsfiddle.net/LvsYc/12330/

希望这对某人有所帮助。

其他回答

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>

单层解决方案:

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

<img id=“blah”alt=“your image”width=“100”height=“100”/><输入类型=“文件”onchange=“document.getElementById('blah').src=window.URL.createObjectURL(this.files[0])”>

生成的URL如下:

blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345

使用jquery预览多个文件

$(文档).ready(函数){$('#image').change(function(){$(“#frames”).html(“”);对于(var i=0;i<$(this)[0].files.length;i++){$(“#frames”).append('<img src=“'+window.URL.createObjectURL(this.files[i])+'”width=“100px”height=“100px“/>');}});});<head><script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js“></script></head><body><input-type=“file”id=“image”name=“image[]”多个/><br/><div id=“frames”></div></body>

如果您使用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>
  )
}
<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>