Solution:
The above code is able to receive image(in the form of base64 string) along with another key called as ‘session-key’. The send image is then stored as jpeg file in anvil’s table.
Managed to create HTTP API endpoint on Anvil’s server code.
# Upload images as base64 string encapsulated in JSON data in HTTP
@anvil.server.http_endpoint("/v1/base64ImageUpload",methods=["POST","OPTIONS"],enable_cors=True)
def base64ImageUploadInDB():
if anvil.server.request.method == 'OPTIONS':
r = anvil.server.HttpResponse()
r.headers['Access-Control-Allow-Origin'] = '*'
r.headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
r.headers['Access-Control-Request-Method'] = '*'
r.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
return r
else:
print(anvil.server.request.body_json)
base64_image_str = anvil.server.request.body_json['image'][0]
session_key = anvil.server.request.body_json['session-key']
actual_image = base64.b64decode(base64_image_str)
uploaded_image_blob = anvil.BlobMedia(content_type="image/jpeg", content=actual_image, name=f"{session_key}.jpg")
app_tables.images.add_row(uploaded_image=uploaded_image_blob)
responsePayload = {'status':'Image uploaded to app_tables','session_key':session_key}
return anvil.server.HttpResponse(201,responsePayload)
The request payload looks as follows:
Headers :
Content-Type : application/json (Compulsory)
Accept: application/json
Data
{
“image”:"/9jdkladhdasjkhdcashddhsaaaa==",
“session-key”:“sess-101”
}
Note:
OPTIONS is used to handle CORS error preflight prerequisites.
If you are using Ionic as front-end, add your anvil public url in network_security_config.xml
Front end code:
public testAPI(){
var sessionData = {
"image" : /*Your image as base64 string*/,
"session-key":/*Any random value*/
};
var httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
}
var headers = new HttpHeaders().set('Content-Type','application/json');
this.http.post('https://testapp.anvil.app/_/api/v1/base64ImageUpload',sessionData,httpOptions).subscribe(
res=>alert(JSON.stringify(res))
)
}
Contents of network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">https://testapp.anvil.app</domain>
</domain-config>
</network-security-config>