Как получить байтовый массив из файла в activJS - PullRequest
2 голосов
/ 06 мая 2019

У меня есть форма для загрузки изображения Аватара, и я должен отправить файл изображения в формате двоичной строки;до сих пор я пытался ReadAsBinaryString из FileReader, но он не работает :( вот мой код:

<form onSubmit={this.onFormSubmit}>
      <div className="row justify-content-center mb-2">
           <input type="file" id="avatar"  accept="image/png, image/jpeg" 
            onChange={this.uploadedImage} />
           <button type="submit" className="btn btn-sm btn-info">Send</button>
       </div>
  </form>

, и именно так я пытаюсь использовать ReadAsBinaryString в uploadedImage функции:

uploadedImage(e) {
    let reader = new FileReader();
    let file = e.target.files[0];
    console.log(file); //I can see the file's info
    reader.onload= () => {
        var array = new Uint32Array(file);
        console.log("_+_array:",array); // the array is empty!
        var binaryString = String.fromCharCode.apply(null,array) ;
        console.log("__binaryString:",binaryString);
      this.setState({
        file: binaryString
      },()=>{
        console.log(this.state.file);//ergo file is set to an empty image
    });
    }
    reader.readAsArrayBuffer(file)
}

Итак, чтобы подвести итог, я получил файл, но не могу преобразовать его в байтовый массив; есть ли что-то не так с этим кодом или этот подход совершенно не так?

Ответы [ 2 ]

1 голос
/ 06 мая 2019

Этот подход работал для меня:

function readFileDataAsBase64(e) {
    const file = e.target.files[0];

    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (event) => {
            resolve(event.target.result);
        };

        reader.onerror = (err) => {
            reject(err);
        };

        reader.readAsDataURL(file);
    });
}

Вы можете позвонить reader.readAsBinaryString(), если хотите использовать двоичную строку. Подробнее здесь: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

0 голосов
/ 06 мая 2019

Вы пытаетесь прочитать данные файла, используя переменную file, которая содержит информацию о файле , а не содержимое файла .Попробуйте что-то вроде следующего:

Документация FileReader

uploadedImage(e) {
    let reader = new FileReader();
    let file = e.target.files[0];
    console.log(file); //I can see the file's info
    reader.onload= () => {
        var array = new Uint32Array(reader.result); // read the actual file contents
        console.log("_+_array:",array); // the array is empty!
        var binaryString = String.fromCharCode.apply(null,array) ;
        console.log("__binaryString:",binaryString);
      this.setState({
        file: binaryString
      },()=>{
        console.log(this.state.file);//ergo file is set to an empty image
    });
    }
    reader.readAsArrayBuffer(file)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...