Support Questions

Find answers, ask questions, and share your expertise
Announcements
Celebrating as our community reaches 100,000 members! Thank you!

How to convert text file to ByteArray and send it via API

avatar
Explorer

Hi,

kindly need your support in below,

 

I have Text file, I have to convert it to byteArray and send it through REST API, I tried many ways to convert the file to byteArray, last one is:
- ExecuteScript with below code:
import base64
import codecs

with codecs.open('/path/to/input/file.txt', 'r', encoding='utf-8') as file:
file_content = file.read()
file_bytes = file_content.encode('utf-8')
encoded_bytes = base64.b64encode(file_bytes)
encoded_string = encoded_bytes.decode('utf-8')

flowFile = session.putAttribute(flowFile, 'fileContent', encoded_string)
session.transfer(flowFile, REL_SUCCESS)

 

but still get error: utf-8' codec can't decode byte 0xff in position 0: unexpected code byte in <script> at line number 6

 

REST API Config:
HTTP Method: POST
API URL:.....
Request Content-Type: application/octet-stream

authentication User: username

 authentication password: password

 

we applied it in VB.net as below:
Function CallApi(APIURL As String,filepath As String) As String

Dim req As WebRequest = WebRequest.Create(APIURL)
Dim txtfile = File.ReadAllBytes(filepath"file.txt")
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
req.Headers("Authorization") = "Basic " & Convert.ToBase64String(Encoding.[Default].GetBytes("username:password"))
req.Method = "POST"
req.ContentType = "application/octet-stream"
Dim byteArray As Byte() = txtfile
req.ContentLength = byteArray.Length
Dim dataStream As Stream = req.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
' response
Dim resp As WebResponse = req.GetResponse()
Dim s As Stream = resp.GetResponseStream()
Dim sr As StreamReader = New StreamReader(s, Encoding.UTF8)
Dim doc As String = sr.ReadToEnd()
Return doc
End Function


Any suggestions may help me to achieve this?

1 REPLY 1

avatar
Community Manager

@MukaAddA, Welcome to our community! To help you get the best possible answer, I have tagged in our NiFi experts @SAMSAL @cotopaul @steven-matison who may be able to assist you further.

Please feel free to provide any additional information or details about your query, and we hope that you will find a satisfactory solution to your question.



Regards,

Vidya Sargur,
Community Manager


Was your question answered? Make sure to mark the answer as the accepted solution.
If you find a reply useful, say thanks by clicking on the thumbs up button.
Learn more about the Cloudera Community: