Giter VIP home page Giter VIP logo

Comments (7)

ReLrO avatar ReLrO commented on July 17, 2024 5
<ReactS3Uploader
            getSignedUrl={this._signUrl}
            accept='image/*'
            uploadRequestHeaders={{ 'x-amz-acl': 'public-read' }}
            preprocess={this._onUploadStart}
            onError={this._uploadOnError}
            onFinish={this._uploadOnFinish}
            contentDisposition='auto'
            className='file-input__file'
            id='input-file' />
_onUploadStart (file, cb) {
    this.props.startImageUpload(file)
    let fileName = file.name.replace(/\.[^/.]+$/, '')
    // Load the image
    let reader = new FileReader()
    reader.onload = (readerEvent) => {
      let image = new Image()
      image.onload = (imageEvent) => {
        // Resize the image
        let canvas = document.createElement('canvas')
        let maxSize = 1050
        let width = image.width
        let height = image.height
        if (width > height) {
          if (width > maxSize) {
            height *= maxSize / width
            width = maxSize
          }
        } else {
          if (height > maxSize) {
            width *= maxSize / height
            height = maxSize
          }
        }
        canvas.width = width
        canvas.height = height
        canvas.getContext('2d').drawImage(image, 0, 0, width, height)
        let dataUrl = canvas.toDataURL('image/jpeg')
        let resizedImage = this._dataURLToBlob(dataUrl)
        resizedImage.lastModifiedDate = new Date()
        resizedImage.name = file.name
        cb(resizedImage)
      }
      image.src = readerEvent.target.result
    }
    reader.readAsDataURL(file)
  }
  _dataURLToBlob (dataURL) {
    if(typeof window !== 'undefined'){
      let BASE64_MARKER = ';base64,'
      if (dataURL.indexOf(BASE64_MARKER) === -1) {
        let parts = dataURL.split(',')
        let contentType = parts[0].split(':')[1]
        let raw = parts[1]
        return new Blob([raw], {type: contentType})
      }

      let parts = dataURL.split(BASE64_MARKER)
      let contentType = parts[0].split(':')[1]
      let raw = window.atob(parts[1])
      let rawLength = raw.length
      let uInt8Array = new Uint8Array(rawLength)

      for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], {type: contentType})
    }
  }

Looking at my code now, I am not sure you need the image.src = readerEvent.target.result and reader.readAsDataURL(file) that come after the callback. You can test it though.

from react-s3-uploader.

kunovsky avatar kunovsky commented on July 17, 2024 3

For reference here is how I was able to get this working correctly

     // In The Uploader Component

    <ReactS3Uploader preprocess={preprocess} ... />

    // In The Higher Order Component (we pass this as the "preprocess" call back to the uploader component)

    function _preprocessFile(file, next) {
      compressFile(file, next, { format: 'image/jpeg' });
    }

    // In A File Upload Util

    function dataURItoBlob(dataURI, format) {
      const binary = atob(dataURI.split(',')[1]);
      const array = [];
      for (let i = 0; i < binary.length; i++) { // eslint-disable-line
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: format });
    }

    function compressFile(file, next, options) {
        const { format } = options;
        const img = new Image();
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');

        img.onload = () => {
          const { width, height } = img;
          canvas.width = width / 2;
          canvas.height = height / 2;
          ctx.drawImage(img, 0, 0, width / 2, height / 2);
          next(new File([dataURItoBlob(canvas.toDataURL(format, 0.5))], file.name, { type: format }));
        };
        img.src = URL.createObjectURL(file);
     }

from react-s3-uploader.

TrejGun avatar TrejGun commented on July 17, 2024 1

@ReLrO
Thanks, you helped me a lot!

from react-s3-uploader.

seanadkinson avatar seanadkinson commented on July 17, 2024

Looks like a blob can be sent to xhr.send, so have you tried just setting a name and type on the blod, and passing it to the callback?

from react-s3-uploader.

ReLrO avatar ReLrO commented on July 17, 2024

Yes. That works. Thank you very much! :)

from react-s3-uploader.

TrejGun avatar TrejGun commented on July 17, 2024

@seanadkinson Can you please give an example?

const img = new Image();
img.src = "data:image/png;base64,...";
img.name = "name.png"
img.type = "image/png";
new S3Upload({
    files: [img],
    ...
});

doesn't work for me
I mean I can upload it but when I'm trying to open it, it is broken

LvfiAmvEkLlqphQ71QbGname.png

@ReLrO how did you manage to make it work?

from react-s3-uploader.

isanjosgon avatar isanjosgon commented on July 17, 2024

Thanks @kunovsky :)

from react-s3-uploader.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.