Convert file stream to base64 python - python

I have read the file stream of a zip file by the following code:
file = open(source_url, "rb")
data = file.read()
file.close()
byte_arr = base64.b64encode(data)
Now I am trying to call a webservice which accepts base64Binary format of data (byte array written in java). If I send byte_arr to the web-service I get client error:
Fault env:Client: Caught exception while handling request: unexpected element type: expected={http://www.w3.org/2001/XMLSchema}base64Binary, actual={http://www.w3.org/2001/XMLSchema}string
Please suggest why is base64 module not working for me.
type(byte_arr) is still string.
With thanks,
Sandhya

I guess there's nothing wrong with your base64 encoding. It seems like it is not embedded in a correct XML document. Probably the error is when you send your data, maybe you should check that piece of code.

Related

Cannot properly decode Base64 string from Power Apps to audio file

I am trying to properly decode a Base64 string from Power Apps to an audio file. The point is: I do decode it and I can play it. But as soon as I try to convert it using ffmpeg or any website, all kind of errors are thrown. I have tried changing the formats too (aac, weba, m4a, wav, mp3, ogg, 3gp, caf), but none of them could be converted to another format.
PS: If I decode the string (which is too big to post here) directly using a website, then the audio file can finally be converted, indicating that the issue is in the code or even in the Python library.
===============
CODE ===============
import os
import base64
mainDir = os.path.dirname(__file__)
audioFileOGG = os.path.join(mainDir, "myAudio.ogg")
audioFile3GP = os.path.join(mainDir, "myAudio.3gp")
audioFileAAC = os.path.join(mainDir, "myAudio.aac")
binaryFileTXT = os.path.join(mainDir, 'binaryData.txt')
with open(binaryFileTXT, 'rb') as f:
audioData = f.readlines()
audioData = audioData[0]
with open(audioFileAAC, "wb") as f:
f.write(base64.b64decode(audioData))
Result: the audio file is playable, but it cannot be converted to any other format (I need *.wav).
What am I missing here?
I found the issue myself: in order to decode the Base64 string, one must remove the header first (eg.: "data:audio/webm;base64,"). Then it works!

Covert SAP XSTRING to a doc file?

I'm working in an application which has SAP RFC which returns doc files as XSTRINGs. And also there is a client application written in python that sends request to SAP RFC to get doc files. So my question is, in python, how can i convert XSTRING to a doc file?.
Response Header's content type is application/msword; and charset=utf-8
This answer was given by the OP inside his own question, so I have moved it here to fit StackOverflow principles.
Answer to my own question :
Even though SAP RFC returns a variable of type xstring, Python receives it in base64. In order to convert base64 string to doc, first I decoded base64 string and it gave me output in RTF. Then I wrote RTF bytes to a .rtf file. RTF files can be opened from most of the word processing tools. Therefore I was able to open .rtf file from word processing tools.
Following is code I wrote for conversion:
from base64 import b64decode
base64_resp = response_json['data']
bytes_rtf = b64decode(base64_resp, validate=True)
f = open(rtf_filename, 'wb')
f.write(bytes_rtf)
f.close()

Python method like File.WriteAllBytes() in .Net

There is a .net API sending the byte data as a string in JSON, I am using a python API to read it and write it in a file.
a = io.BytesIO(b"JVBERi0xLjQNJcjIyMjIyMg...")
with open('test.pdf','wb') as g:
g.write(a.getvalue())
I created a file with this code but unable to open the file.
I need another way of doing the same.
instead of using io.BytesIO use base64.
import base64
data = "strin data"
base64_data =base64.b64decode(data)
with open(filename,'wb') as f:
f.write(base64_data)

Saving uploaded binary to local file

I'm trying to upload files from a javascript webpage, to a python-based server, with websockets.
In the JS, this is how I'm transmitting the package of data over the websocket:
var json = JSON.stringify({
'name': name,
'iData': image
});
in the python, I'm decoding it like this:
noJson = json.loads(message)
fName = noJson["name"]
fData = noJson["iData"]
I know fData is in unicode format, but when I try to save the file locally is when the problems begin. Say, I'm trying to upload/save a JPG file. Looking at that file after upload I see at the beginning:
ÿØÿà^#^PJFIF
the original code should be:
<FF><D8><FF><E0>^#^PJFIF
So how do I get it to save with the codes, instead of the interpreted unicode characters?
fd = codecs.open( fName, encoding='utf-8', mode='wb' ) ## On Unix, so the 'b' might be ignored
fd.write( fData)
fd.close()
(if I don't use the "encoding=" bit, it throws a UnicodeDecodeError exception)
Use 'latin-1' encoding to save the file.
The fData that you are getting already has the characters encoded, i.e. you get the string u'\xff\xd8\xff\xe0^#^PJFIF'. The latin-1 encoding will literally convert all codepoints between U+00 and U+FF to a single char, and fail to convert any codepoint above U+FF.

Handling B64 encoded data in Python

In my Google App Engine based app, I am fetching data from a SOAP webservice.
The problem is that one of the tag contains binary 64 encoded data. I decode it using
decodedStr = base64.b64decode(str(content))
It seems that the decoding is not done correctly a I get garbage data in decodeStr. I think the problem is that the content string is falsely parsed as a unicode string instead of simple byte string
Can any Python guru tell me how to handle b64 encoded data in Python?
For now I am using this workaround
fileContent = str(fileContent)
fileContent = fileContent[3:-3]
self.response.out.write(base64.b64decode(fileContent))
You could try using base64.decodestring or if you were passed an url base64.urlsafe_b64decode.
Make sure that the data is not in base16 or base32.
Strange. If the content were not b64 encoded, the call to decode should raise a TypeError exception. I assume that's not happening?
Which would lead me to wonder how you know the resulting decodedStr is not what your after?

Categories