- Retrieving a file from doclinks is straightforward. We can pass the doclink URL to ‘File’ object as shown below.
file=File("docklink-filepath")- However, if the attachments are using an S3 bucket, then we cannot directly fetch ‘File’ object from URL.
- Few additional steps are required to convert as file before sending or uploading to an API
- Get the byte array of attachment from S3 bucket
- Create a temporary file in server or pod
- Create ‘File-output stream’ of the temporary file
- Write the byte array into the ‘File-output stream’.
- Upload the ‘File-output stream’ to REST API to send as file attachment.
- Delete the temporary file
Source Code:
from com.ibm.tivoli.maximo.cos import COSApifrom java.io import File, FileOutputStream, FileInputStreamfrom java.net import URL, HttpURLConnection;from org.apache.http.entity.mime import MultipartEntityBuilder;
cosApi = COSApi(False)bucketname = service.getProperty(mxe.cosbucketname)urlString = filePath.split()fileName = urlString[-1]
#Create Temporary File in PodFILEPATH = "root\maximo\temp\fileName.txt";uploadFile = File(FILEPATH);uploadFile.createNewFile();fos = FileOutputStream(uploadFile);
## Option - 1
#Get byteArray from S3 BucketdocBytes=cosApi.getFile(bucketname,fileName)
# Write the Bytes to File Outputstreamfos.write(docBytes);print(Successfully+ byte inserted);# Close the file connectionsfos.close();
'''## Option - 2# Get Input Stream from s3 bucketfis=cosApi.streamFile(bucketname,fileName)
byteRead=0#Read byte by bytewhile ((byteRead = fis.read()) != -1) #Write byte by byte fos.write(byteRead)'''
#Upload File Outputstream to REST APIbuilder = MultipartEntityBuilder.create();builder.addBinaryBody(file, uploadFile);entity = builder.build();
url = URL("https:\\clientdomainhostname\restapi\fileupload");conn = url.openConnection();conn.setDoOutput(True);conn.setRequestMethod(POST);conn.addRequestProperty(Content-Length, str(entity.getContentLength()));fos = conn.getOutputStream();entity.writeTo(fos);fos.close();conn.connect();conn.getInputStream().close();statusCode = conn.getResponseCode();
#Delete the Temporary File After UploaduploadFile.delete()
No comments:
Post a Comment