最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to turn multiple files into base64 string? - Stack Overflow

programmeradmin0浏览0评论

i have a ponent like this

<input type="file" multiple @change="toBase64Handler($event)">

<script>
 data() {
  return {
     files: [],
   }
 },
 methods: {
  tobase64Handler(event) {
   // the code
  }
 }
</script>

and i would like to turn all of the selected files into base64 string something like this:

files: [
  {
   selectedFile: 'ajsdgfauywdljasvdajsgvdasdo1u2ydfouayvsdlj2vo8ayasd...'
  },
  {
   selectedFile: 'askdhgoiydvywdljasvdajsgvdasdo1u2ydfoakjgsfdjagswsd...'
  },
  {
   selectedFile: '12edashjvlsljasvdajsgvdasdo1u2ydfouayvsdlj2vo8ayfsd...'
  },
]

how do i achieve that?

i have a ponent like this

<input type="file" multiple @change="toBase64Handler($event)">

<script>
 data() {
  return {
     files: [],
   }
 },
 methods: {
  tobase64Handler(event) {
   // the code
  }
 }
</script>

and i would like to turn all of the selected files into base64 string something like this:

files: [
  {
   selectedFile: 'ajsdgfauywdljasvdajsgvdasdo1u2ydfouayvsdlj2vo8ayasd...'
  },
  {
   selectedFile: 'askdhgoiydvywdljasvdajsgvdasdo1u2ydfoakjgsfdjagswsd...'
  },
  {
   selectedFile: '12edashjvlsljasvdajsgvdasdo1u2ydfouayvsdlj2vo8ayfsd...'
  },
]

how do i achieve that?

Share Improve this question edited Nov 20, 2019 at 15:02 dunhilblack asked Nov 20, 2019 at 14:50 dunhilblackdunhilblack 3051 gold badge5 silver badges14 bronze badges 2
  • Possible duplicate of How to convert file to base64 in JavaScript? – Fab Commented Nov 20, 2019 at 15:02
  • i cant seem to access the index of the FileList :/ – dunhilblack Commented Nov 20, 2019 at 15:09
Add a ment  | 

2 Answers 2

Reset to default 8

You can loop though the files call a helper method toBase64, push all Promises to an array and resolve all of them:

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

  async tobase64Handler(files) {
    const filePathsPromises = [];
    files.forEach(file => {
      filePathsPromises.push(this.toBase64(file));
    });
    const filePaths = await Promise.all(filePathsPromises);
    const mappedFiles = filePaths.map((base64File) => ({ selectedFile: base64File }));
    return mappedFiles;
  }

this should do the trick: JSON.stringify(files) you can read more about it here. If you later want to turn it back into the original array, object, or value then you'd do JSON.parse(files). you can read more about it here

UPDATE: turns out I was wrong and JSON.stringify/parse don't work with files(thanks for the info @patrick evans). found this answer which seems better (the one by @ahmed hamdy)

发布评论

评论列表(0)

  1. 暂无评论