Загрузить фото-блоб на s3 - PullRequest
0 голосов
/ 25 марта 2020

У меня есть приложение ioni c, и я пытаюсь загрузить обрезанную фотографию на S3, но по какой-то причине файл открывается неправильно. Я попытался преобразовать изображение base64 в blob, но последний шаг, похоже, тоже не работает.

  1. Я получаю доступ к файлу из плагина cordova-plugin-camera, который возвращает Base64 encoding of the image data, or the image file URI.
  2. Затем он обрезается с помощью плагина cordova-plugin-crop, который возвращает "путь к изображению".

Этот путь изображения затем передается на showCroppedImage() ниже.

showCroppedImage(ImagePath) {
  this.isLoading = true;
  var copyPath = ImagePath;
  var splitPath = copyPath.split('/');
  var imageName = splitPath[splitPath.length - 1];
  var filePath = ImagePath.split(imageName)[0];

  this.filePlugin.readAsDataURL(filePath, imageName).then(base64 => {
    this.imageSrc = base64;
    this.canSave = true
    // this.file = base64
    this.file = this.dataURItoBlob(base64) // DOES NOT WORK
    this.isLoading = false;
  }, error => {
    alert('Error in showing image' + error);
    this.isLoading = false;
  });
}



dataURItoBlob() {
  const parts = dataURI.split(';base64,');
  const imageType = parts[0].split(':')[1];

  let byteCharacters = atob(parts[1]); // displays data when printed
  const byteNumbers = new Array(byteCharacters.length); // displays data when printed
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers); // displays data when printed
  const blob = new Blob([byteArray], {type: imageType});  // displays nothing when printed!
  return blob
}

Я что-то упустил? Этот блоб пуст, когда я его печатаю, и если я пытаюсь загрузить данные base64 из showCroppedImage() в S3, файл содержит все данные, но загружается как текст, а не изображение.

Мой метод для загрузки на S3 это:

uploadfile(event, type) {
  let key = `${ this.key }/${ this.new_doc_name }`;

  console.log("key", key)
  let body = this.file // I set this in `showCroppedImage()`
  let params = {
    Key: key,
    Body: body,
    Bucket: 'bucket-name',
    BaseEncoding: 'base64'
  };

  // alert(JSON.stringify(params))

  console.log("Uploading photo:", params)

  this.s3.upload(params).then( (data) => {

    let doc : IClientDoc = { name: null, url: null, client_id: null}

    console.log(data)
    alert(JSON.stringify(data))

    doc.name = this.new_doc_name
    doc.url = data['Location']
    doc.client_id = this.client.id

    this.clientDocService.create(doc).subscribe(() => this.dismiss(true))
  })
}

1 Ответ

0 голосов
/ 25 марта 2020

Мне удалось решить эту проблему с помощью Buffer. Я установил буфер через npm и импортировал его как import * as Buffer from 'buffer'. Затем я обновил uploadFile() до следующего:

uploadFile(event, type) {
  let key = `${ this.key }/${ this.new_doc_name }`;

  // I set this.file in `showCroppedImage()`
  let f = this.file.replace(/^data:image\/\w+;base64,/, "")

  const base64Data = Buffer.Buffer.from(f, 'base64');

  const fileType = this.file.split(';')[0].split('/')[1];

  let params = {
    Key: key,
    Body: base64Data,
    Bucket: 'bucket-name',
    ContentEncoding: 'base64',
    ContentType: fileType
  };

  this.s3.upload(params).then( (data) => {
    let doc : IClientDoc = { name: null, url: null, client_id: null}
    doc.name = this.new_doc_name
    doc.url = data['Location']
    doc.client_id = this.client_id

    this.clientDocService.create(doc).subscribe(() => this.dismiss(true))
  })
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...