jquery 图像转换为Base64

xzv2uavs  于 2023-02-12  发布在  jQuery
关注(0)|答案(8)|浏览(365)
<input type="file" id="asd"/>

我想在用户选择base64后获得该图像(在提交表单之前)
比如:

$(input).on('change',function(){
  var data = $(this).val().base64file(); // it is not a plugin is just an example
  alert(data);
});

我读了关于文件API和其他东西,我想要一个简单的和跨浏览器的解决方案(IE6/IE7明显排除)
任何帮助都很感激谢谢。

huwehgph

huwehgph1#

function readFile() {
  
  if (!this.files || !this.files[0]) return;
    
  const FR = new FileReader();
    
  FR.addEventListener("load", function(evt) {
    document.querySelector("#img").src         = evt.target.result;
    document.querySelector("#b64").textContent = evt.target.result;
  }); 
    
  FR.readAsDataURL(this.files[0]);
  
}

document.querySelector("#inp").addEventListener("change", readFile);
<input id="inp" type="file">
<p id="b64"></p>
<img id="img" height="150">

(**P. S:**base64编码图像(字符串)原始图像数据大小的4/3)
Check this answer for multiple images upload.
浏览器支持:www.example.comhttp://caniuse.com/#search=file%20api
更多信息:https://developer.mozilla.org/en-US/docs/Web/API/FileReader

c86crjj0

c86crjj02#

正是你所需要的:)你可以选择回调版本或承诺版本。请注意,承诺将在IE中工作,只有与承诺polyfill库。你可以把这个代码一次在一个页面上,这个函数将出现在你的所有文件。
loadend事件在加载资源的进程停止时触发(例如,在分派了“error”、“abort”或“load”之后)
回调版本

File.prototype.convertToBase64 = function(callback){
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    callback(e.target.result, e.target.error);
                };   
                reader.readAsDataURL(this);
        };

        $("#asd").on('change',function(){
          var selectedFile = this.files[0];
          selectedFile.convertToBase64(function(base64){
               alert(base64);
          }) 
        });

承诺版本

File.prototype.convertToBase64 = function(){
         return new Promise(function(resolve, reject) {
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    resolve({
                      fileName: this.name,
                      result: e.target.result, 
                      error: e.target.error
                    });
                };   
                reader.readAsDataURL(this);
        }.bind(this)); 
    };

    FileList.prototype.convertAllToBase64 = function(regexp){
      // empty regexp if not set
      regexp = regexp || /.*/;
      //making array from FileList
      var filesArray = Array.prototype.slice.call(this);
      var base64PromisesArray = filesArray.
           filter(function(file){
             return (regexp).test(file.name)
           }).map(function(file){
             return file.convertToBase64();
           });
      return Promise.all(base64PromisesArray);
    };

    $("#asd").on('change',function(){
      //for one file
      var selectedFile = this.files[0];
      selectedFile.convertToBase64().
          then(function(obj){
            alert(obj.result);
          });
      });
      //for all files that have file extention png, jpeg, jpg, gif
      this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
            objArray.forEach(function(obj, i){
                  console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
            });
      });
    })

超文本标记语言

<input type="file" id="asd" multiple/>
gt0wga4j

gt0wga4j3#

<input type="file" onchange="getBaseUrl()">
function getBaseUrl ()  {
    var file = document.querySelector('input[type=file]')['files'][0];
    var reader = new FileReader();
    var baseString;
    reader.onloadend = function () {
        baseString = reader.result;
        console.log(baseString); 
    };
    reader.readAsDataURL(file);
}
6kkfgxo0

6kkfgxo04#

在这种情况下,使用Deferred Object并返回promise非常有用:

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;
    if (files && files[0]) {
        var fr= new FileReader();
        fr.onload = function(e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL( files[0] );
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

上述函数可以这样使用:

var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
    alert(base64Data);
});

或者在您的情况下:

$(input).on('change',function(){
  readImage($(this)).done(function(base64Data){ alert(base64Data); });
});
wa7juj8i

wa7juj8i5#

函数使用jquery将图片转换成base64(你可以转换成vanila js)。希望对你有帮助!
用法:输入是你的nameId输入有文件图像

<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

async function converImageToBase64(inputId) {
  let image = $('#'+inputId)[0]['files']

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

    return new Promise(resolve => {
      reader.onload = ev => {
        resolve(ev.target.result)
      }
      reader.readAsDataURL(image[0])
    })
  }
}

async function proccessData() {
  const image = await converImageToBase64('asd')
  console.log(image)
}

</script>

示例:将图像转换为Base64('yourFileInputId')
https://codepen.io/mariohandsome/pen/yLadmVb

pnwntuvh

pnwntuvh6#

// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

/* Simple */
function previewImage( image, preview, string )
{

    var preview     = document.querySelector( preview );
    var fileImage   = image.files[0];

    var reader      = new FileReader();

    reader.addEventListener( "load", function() {

        preview.style.height    = "100";
        preview.title           = fileImage.name;

        // convert image file to base64 string
        preview.src             = reader.result;

        /* --- */

        document.querySelector( string ).value = reader.result;                    

    }, false );

    if ( fileImage )
    {
        reader.readAsDataURL( fileImage );
    }

}

document.querySelector( "#imageID" ).addEventListener( "change", function() {

    previewImage( this, "#imagePreviewID", "#imageStringID" );

} )
/* Simple || */
<form>

    File Upload: <input type="file" id="imageID" /><br />
    Preview: <img src="#" id="imagePreviewID" /><br />    
    String base64: <textarea id="imageStringID" rows="10" cols="50"></textarea>

</form>

codesanbox

erhoui1w

erhoui1w7#

适用于现代浏览器(不支持IE)

Html文件输入

<style>
.upload-button {
  background-color: grey;
}

.upload-button input{
  display:none;
}
</style>
<label for="upload-photo" class="upload-button">
    Upload file
    <input
     type="file"
     id="upload-photo"
    </input>
</label>

JS系统

document.getElementById("upload-photo").addEventListener("change", function({target}){
 if (target.files && target.files.length) {
      try {
        const uploadedImageBase64 = await convertFileToBase64(target.files[0]); 
        //do something with above data string 
      } catch() {
        //handle error
      }
    }
})

function convertFileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
  });
}
u3r8eeie

u3r8eeie8#

const FR = new FileReader();
    
  FR.addEventListener("load", function(evt) {
    document.querySelector("#img").src         = evt.target.result;
    document.querySelector("#b64").`textContent` = evt.target.result;
  }); 
    
  FR.readAsDataURL(this.files[0]);
< img id="inp" src="https://tlc.ca/pricing-tool/images/logo.png">
<p id="b64"></p>
<img id="img" height="150">
  • 列表项

相关问题