HowTo: Upload an image, video, or audio file via an API object (2024)

This document explains how to upload images, videos, or audios using an API object,and provides a brief overview about it.

An API object makes it possible to upload Image, Video, Audio or BlobFile files.

To achieve this, two things must be taken into account:

  • Two entries are generated from a service that has some parameter with the in operator of Image, Video, Audio or BlobFile type: one to upload the file (which is generated automatically) and another one to send that file to the database.
  • You can use any tool that allows you to perform an HTTP POST with the binary to upload the file, for example, Postman.

Samples

Suppose you want to upload an image. To do so, follow these steps:

Step 1

Consider the following Transaction defined as a Business Component:

Picture{ PictureId* (Type:Id) PictureName (Type:VarChar) PictureImage (Type:Image)}

Step 2

Create a Procedure called InsertPicture and define the following:

Variables:

Picture (Type:Picture)PictureId (Type:Attribute:PictureId)PictureName (Type:Attribute:PictureName)PictureImage (Type:Attribute:PictureImage)Response (Type:VarChar)

Rules:

Parm(in:&PictureId, in:&PictureName, in:&PictureImage, out:&Response);

Source:

&Picture.PictureId = &PictureId&Picture.PictureImage = &PictureImage&Picture.PictureName = &PictureNameif &Picture.Insert() &Response = 'Insert OK' commitelse &Response = 'Insert ERROR' rollbackEndif

Step 3

Create the API object called “APIPicture” and define the following:

Variables:

PictureId (Type:Attribute:PictureId)PictureName (Type:Attribute:PictureName)PictureImage (Type:Attribute:PictureImage)Response (Type:VarChar)

Service Source:

Picture{ [RestMethod(POST)] [RestPath("/ServiceUpload")] InsertImage(in:&PictureId, in:&PictureName, in:&PictureImage, out:&Response) => InsertPicture(&PictureId, &PictureName, &PictureImage, &Response); }

Step 4

Run the API object (by right-clicking on the APIPicture tab and selecting Run).

Note: If you are using the GeneXus .NET Generator, it is recommended to configure Generate OpenAPI interface = Yes to open the browser with a Swagger user interface before running it.

To continue, you can choose one of the following options:

  • Use Postman to prototype.
  • Use HTTPClient to call the service from a program.

UsingPostman

To use Postman, follow the steps below:

  1. Upload URL to Postman.
  2. Upload the image to the server.
  3. Send the image to the database.

1. Upload URL to Postman

Go to Postman, click on APIs, then click on New, and finally on HTTP Request:

The following will be displayed:

When you click on GET, a dynamic combo will be displayed. Select POST, enter the URL of the API object, and add /gxobject at the end, as shown below:

What is being done is to point to the gxobject method, which is automatically generated by GeneXus and allows you to upload the image to the server.

2. Uploading the image to the server

The steps to upload the image to the server, as shown in image #5, are the following:

  1. Select: Body.
  2. Select: Binary.
  3. Upload the desired image.
  4. Click on the Send button.
  5. Copy what appears in object_id.

3. Sending the image to the database

To send the image to the Database, you will have to use the method that was defined in the API object; in this case, ServiceUpload.

Note:In this example, the method name is ServiceUpload, since aRestPath annotation was defined. If the annotation is left out, the name of your method will be the one that was first defined; in this case, “InsertImage”:http://localhost:8082/KnowledgeBaseInsertImageNETSQLServer/APIPicture/InsertImage

Open a new tab in Postman, copy the URL of the API object, and add /ServiceUpload at the end. Go to Body>raw and type the input variables as shown below:

Note:In PictureImage, the input variable where the image is saved, paste what is shown in object_id (point 5, in Image #5).
In this case, it is: gxupload:90a7109cf31a4e2cbebd40ccac54d36c

By clicking on Send, you will be able to see the Insert OK message. This means that the image was successfully sent to the database. You can run the Picture Transaction to view the inserted record with the image.

Using HTTPClient

You can consume any REST service with GeneXus, whether it's been generated with it or not.

To consume a REST service, take into account the following:

  • In GeneXus, a REST service is consumed using the HttpClient data type. You can have all the objects automatically generated using the OpenAPI import tool.
  • Remember that the appropriate content type headers must be sent using the AddHeader method. For example, for a JSON body, the code should be as follows:
    &httpClient.AddHeader("Content-Type", "application/json")

In addition, since you are trying to upload an image, keep in mind that two HTTP POST methods are required:

  • An HTTP POST "<Object name>/gxobject" (below the URL of the web application) attaching the file to the HTTP request. This returns a reference that you must use to insert the image into the database.
  • Next, run an HTTP POST procedure to the REST by sending a JSON request that includes the information to be processed.

If GAM is enabled, remember to add the mandatory Authorization header. Use theGetAgentServiceHeader methodto get the correct one for your use case. If you want to call it manually, using the Access_token GAM Service, then include:

&httpclient.AddHeader('Authorization', &access_token)

Furthermore, because the JSON format of the Image is provided, it is necessary to use SDTs to load the data to be sent to the service.

In this case, it will be necessary to follow the three steps shown below:

  1. Create SDTs
  2. Create a Procedure
  3. Run the Procedure

1. Create SDTs

Create an SDT named, for example, Imageref, and define the following:

Create another SDT named, for example, InsertImage__postInput with the following structure:

2. Create a Procedure

Create a Procedure and define the following:

Variables:

httpClient (Type: HttpClient)ImagePath (Type: Character)Imageref (Type: Imageref)Ivc (Type: VarChar)Picture (Type: InsertImage__postInput)ref (Type: VarChar)body (Type: VarChar)

Source:

&ImagePath = 'C:\Downloads\Image1.jpg' //add the path to the image.&httpClient.Host ='localhost' //Insert service&httpClient.Port = 8082 //Insert port&httpClient.BaseUrl = 'KnowledgeBaseInsertImageNETSQLServer/APIPicture/' //Insert basepath&httpClient.AddHeader('Content-Type','application/jpg') //AddHeader Method use to up image&httpClient.AddFile(&ImagePath) //The AddFile method adds the contents of the file to the variable holding the file path.&httpClient.Execute('POST','gxobject') //Executes POST HTTP method in the URL path for the gxobject whose information is to be obtained. &lvc = &httpClient.ToString() //Returns the HTML code of the image in the variable &lvc&Imageref.FromJson(&lvc) //loads the &Imageref structure from the contents of the &lvc variable&ref = &Imageref.object_id msg(&ref,status) //add the image data to be uploaded in a variable based on the SDT&Picture.PictureId= 4&Picture.PictureName = 'Image4'&Picture.PictureImage = &ref //PictureImage is where the image is stored, so you must assign the variable &ref. &body = &Picture.ToJson() //Returns a string with the JSON representation for the &Picturemsg(&body,status) &httpClient.AddHeader('Content-Type','application/json')&httpClient.AddString(&body)&httpClient.Execute('POST','ServiceUpload')&lvc = &HttpClient.ToString()msg(&lvc,status)

3.Run the Procedure

In the Procedure, configure its Main program property to 'Yes' and its Call protocol property with the 'Command line' value.

Next,run it. To do so, right-click on the Procedure tab and select Run.

In the Output, you can have details of the result of the procedure, which will be similar to the image:

The Insert OK message means that the image was successfully sent to the database and you will be able to see it in the Web Form of the Picture Transaction.

Considerations

If you run the API object and a tab opens in your browser as shown below:

Select and copy the link to that page. Actually, you will be copying the URL of the API object, which is composed of:

http://{{host}}/{{baseurl}}/{{BasePath}}

Where:

host = localhost:8082
baseurl = KnowledgeBaseInsertImageNETSQLServer
BasePath = APIPicture

Note: This can happen if you are using the GeneXus .NET Generator and the value of theGenerate OpenAPI interface property is not Yes or if you are using any other generator. In any case:

  • You will only have to copy the URL of the API object (http://localhost:8082/KnowledgeBaseInsertImageNETSQLServer/APIPicture) and disregard the rest.
  • Check that the BasePath matches the Services base path property. That is, if Services base path = "APIPicture” the URL must be http://localhost:8082/KnowledgeBaseInsertImageNETSQLServer/APIPicture

Availability

SinceGeneXus 17 Upgrade 9.

See Also

Execute method
BaseUrl property
AddFile method
ToString method
FromJson method
ToJson method

HowTo: Upload an image, video, or audio file via an API object (2024)

FAQs

How to send an image file through API? ›

Option 1: Direct File Upload , From this method you can select form-data and set the type to file. Then select an image file by clicking on the button shown in the value column. The content type is automatically detect by postman but if you want you can set it with a relevant MIME type.

How to upload a file through API? ›

How to Upload Files in Requests Using API?
  1. Step 1: Creating a New Project. Open the Apidog application and create a new Request.
  2. Step 2: Select the Request Method. ...
  3. Step 3: Set the Request Body Content Type. ...
  4. Step 4: Add a File Field to the Request Body. ...
  5. Step 5: Save and Test the Request.
Apr 29, 2024

How to upload an image with Fetch API? ›

To upload files with the Fetch API, we need to create a request body that includes the file data. We can do this using the FormData object, which allows us to append file data to a new FormData instance. const file = fileInput. files[0];

How do I upload an image to API react? ›

To upload image and preview it using React JS we will use the HTML file input for the image input. After taking input the image url is created using URL. createObjectURL() method and store in the useState variable named file. Display the image as preview using the html img tags with the file url in the src prop.

How to upload image in API using Postman? ›

Upload a file to your Postman team
  1. Open a request and select the Body tab.
  2. Select form-data or binary depending on the type of data you want to send with the request.
  3. If you're attaching form data, select File in the dropdown list next to a key name.
  4. Select the test data file you want to use for the request:
Feb 5, 2024

Can files be sent via API? ›

Use the File transfer REST API to upload and download files using HTTP or HTTPS as the transport protocol and to list the contents of a directory. Uploads a file to any back-end application that supports REST APIs over HTTP or HTTPS protocol.

How to send attachment through API? ›

In the Message Body

Open the Attachments panel and click Add Attachment. Click the image to enlarge it. Select the file you want to send. ReadyAPI will ask you if want to cache it in the request.

How to create API file? ›

Choosing your API design tools
  1. In the console, open the navigation menu and click Developer Services. Under API Management, click Gateways.
  2. On the APIs page, click Create API Resource and specify its Name. ...
  3. Click Create to create the new API resource.
  4. Write the backend code. ...
  5. Test the backend code. ...
  6. Deploy.

How to import data through API? ›

Import Data through the REST API
  1. Get the ID for the Corresponding Data Table.
  2. Upload the Input File to a Temporary Location.
  3. Submit an Import Request Job.
  4. View the Status of an Import Request.
  5. Troubleshooting Import Failures. About Statuses for Import Failures. Downloading Failed Import Data.
Apr 12, 2024

How do I send an image to API gateway? ›

Configure parameter mappings for the PUT method
  1. In the Resources panel of your API page, choose PUT.
  2. Choose Integration Request.
  3. Expand URL Path Parameters.
  4. Choose Add path.
  5. For Name, enter bucket.
  6. For Mapped from, enter method. request. ...
  7. Choose the check mark icon at the end of the row.
  8. Repeat steps 4–7.

How do I send data through Fetch API? ›

When you open DevTools in Chrome (Press F12) you'll see that a fetch request has been made to the route users. You can get more data from the request, refer to the https://jsonplaceholder.typicode.com/guide/documentation. POST request using fetch API: The post request is widely used to submit forms to the server.

What is image fetching? ›

An image fetch is the action taken by imgix to retrieve an Origin Image from your image Source. Fetching an Origin Image from an image Source is the most time-consuming task in a request.

How do I send an image using API? ›

Sending the image to the database

To send the image to the Database, you will have to use the method that was defined in the API object; in this case, ServiceUpload. Note: In PictureImage, the input variable where the image is saved, paste what is shown in object_id (point 5, in Image #5).

How to upload video using React JS? ›

To use the endpoint in your application, use the JavaScript Fetch API to call the Cloudinary upload endpoint and pass:
  1. an unsigned upload preset with the upload method options you want to apply for all files.
  2. the file(s) to upload.
  3. other unsigned upload parameters to apply to the selected files (e.g. tags , if needed).

How to send image through HTTP? ›

The send method both dispatches the request to the remote server, and sets its argument as the body of that request. Since you're expecting Base64 encoded image data on your server, you'll first need to convert your image file to Base64 data on the client.

How to send an image in a JSON request? ›

The best you could do with JSON is encode all the raw image data using base 64. That would be making use of 6 bits per byte instead of 8. If you have a MongoDb, you could store the image as a document. If you have an SQL database, it is best to store raw image data using the BLOB type.

How do I send an image file? ›

How To Send Photos Without Losing Quality Using Email
  1. Click on New Email or Compose.
  2. Type the email address of the intended recipient.
  3. Fill in the subject, and optional body text.
  4. Click Attach File, and select the images you want to send.
  5. Click on the Send button when ready.
Mar 12, 2024

Top Articles
10 Of Ford's Most Powerful Engines, Ranked By Horsepower - SlashGear
Forensic Toxicology
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 5832

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.