Sample code for 30+ languages & platforms
PureBasic

REST File Upload (multipart/form-data)

See more REST Examples

Demonstrates how to upload a file using multipart/form-data.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkRest.pb"
IncludeFile "CkStream.pb"

Procedure ChilkatExample()

    success.i = 0

    ; This example requires the Chilkat API to have been previously unlocked.
    ; See Global Unlock Sample for sample code.

    rest.i = CkRest::ckCreate()
    If rest.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Connect to the HTTP server using TLS.
    bTls.i = 1
    port.i = 443
    bAutoReconnect.i = 1
    ; Make sure to replace "www.chilkatsoft.com" with your domain..
    success = CkRest::ckConnect(rest,"www.chilkatsoft.com",port,bTls,bAutoReconnect)
    If success <> 1
        Debug CkRest::ckLastErrorText(rest)
        CkRest::ckDispose(rest)
        ProcedureReturn
    EndIf

    fileStream.i = CkStream::ckCreate()
    If fileStream.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStream::setCkSourceFile(fileStream, "qa_data/jpg/starfish.jpg")

    CkRest::ckAddHeader(rest,"Content-Type","multipart/form-data")

    CkRest::setCkPartSelector(rest, "1")
    CkRest::ckAddHeader(rest,"Content-Type","image/jpg")
    CkRest::ckAddHeader(rest,"Content-Disposition","form-data; name=" + Chr(34) + "filename" + Chr(34) + "; filename=" + Chr(34) + "starfish.jpg" + Chr(34))
    CkRest::ckSetMultipartBodyStream(rest,fileStream)
    CkRest::setCkPartSelector(rest, "0")

    responseBody.s = CkRest::ckFullRequestMultipart(rest,"POST","/the_uri_path_to_receive_the_upload")
    If CkRest::ckLastMethodSuccess(rest) <> 1
        Debug CkRest::ckLastErrorText(rest)
        CkRest::ckDispose(rest)
        CkStream::ckDispose(fileStream)
        ProcedureReturn
    EndIf

    If CkRest::ckResponseStatusCode(rest) <> 200
        Debug "Received error response code: " + Str(CkRest::ckResponseStatusCode(rest))
        CkRest::ckDispose(rest)
        CkStream::ckDispose(fileStream)
        ProcedureReturn
    EndIf

    Debug "File uploaded"


    CkRest::ckDispose(rest)
    CkStream::ckDispose(fileStream)


    ProcedureReturn
EndProcedure