Convert image data to render an image in the brows

2019-03-31 08:45发布

问题:

I am trying to download an encrypted image file from Amazon S3 through a presigned_link with AJAX, and is getting a bunch of image data gibberish.

$(document).on 'click', '.js-download', (event) ->
 event.preventDefault()

 $.ajax
  type: "GET"
  url: event.currentTarget.href
  contentType: 'image/jpeg',
  headers: {
    'x-amz-server-side-encryption-customer-algorithm': 'AES256',
    'x-amz-server-side-encryption-customer-key': customer_key,
    'x-amz-server-side-encryption-customer-key-MD5': customer_key_md5,
  }
  success: (data) ->
    convert_to_image(data)

The ajax data results in a bunch of image data.

����JFIFHH��XICC_PROFILEHLinomntrRGB XYZ � 1acspMSFTIEC sRGB���-HP cprtP3desc�lwtpt�bkptrXYZgXYZ,bXYZ@dmndTpdmdd��vuedL�view�$lumi�meas$tech0rTRC<gTRC<bTRC<textCopyright (c) 1998 Hewlett-Packard CompanydescsRGB IEC61966-2.1sRGB IEC61966-2.1XYZ �Q�XYZ XYZ o�8��XYZ b����XYZ $����descIEC http://www.iec.chIEC http://www.iec.chdesc.IEC 61966-2.1 Default RGB colour space - sRGB.IEC 61966-2.1 Default RGB colour space - sRGBdesc,Reference Viewing Condition in IEC61966-2.1,Reference Viewing Condition in IEC61966-2.1view��_.���\�XYZ L VPW�meas�sig CRT curv........

After getting the data, I'm trying to convert the image data string to jpg image format that will render on the page.

convertToImage(imageData) ->
   data = 'data:image/jpeg,' + btoa(encodeURIComponent(imageData))
   img = document.createElement('img')
   img.src = data
   a = document.createElement('a')
   a.setAttribute("download", "image.jpeg")
   a.setAttribute("href", data)
   a.appendChild(img)
   document.body.appendChild(a)

The link returns: 
'<img src="data:image/jpeg,JUVGJUJGJUJEJUVGJUJGJUJEJUVGJUJGJUJEJUVGJUJ.......>'

The image is not showing up correctly. I've been trying various other methods to convert the image data, but it's not working. Any help would be appreciated.

回答1:

That's not an image data string. It's a binary image data blob in the JPEG format, which (evidently) happens to have some strings in its header.

btoa (base64) is for binary data, not URIs. Calling encodeURIComponent on a jpeg blob will garble it, and I'm kind of surprised it works at all.

Removing that call should fix your problem.