Sample code for 30+ languages & platforms
Swift

Box.com Upload File

See more Box Examples

Demonstrates how to upload a file to box.com.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    // ------------------------------------------------------------------------------------------
    // Important:
    // See this information about Box.com Service Accounts
    // Box.com will automatically generate a Service Account where the name of the account is the name of your App.� 
    // When you make API calls, it is for this service account, and the files that exist and what you see are not the same as your normal account.
    // ------------------------------------------------------------------------------------------

    let rest = CkoRest()!

    //   Provide a previously obtained OAuth2 access token.
    let oauth2 = CkoOAuth2()!
    oauth2.accessToken = "BOX_ACCESS_TOKEN"
    rest.setAuthOAuth2(authProvider: oauth2)

    // First, make the initial connection.
    // A single REST object, once connected, can be used for many Box REST API calls.
    // The auto-reconnect indicates that if the already-established HTTPS connection is closed,
    // then it will be automatically re-established as needed.
    var bAutoReconnect: Bool = true

    // ----------------------------------------------------------------------
    // IMPORTANT: Note that the domain is "upload.box.com", not "api.box.com"
    // ----------------------------------------------------------------------
    success = rest.connect(hostname: "upload.box.com", port: 443, tls: true, autoReconnect: bAutoReconnect)
    if success != true {
        print("\(rest.lastErrorText!)")
        return
    }

    // The request body uses the "multipart/form-data" format to transmit two "parts". 
    // The first part is called "attributes" and contains a JSON object with information about the file, including the name of the file 
    // and the ID of the parent folder. The second part contains the contents of the file. 
    // (Note that the name of the second "part" is ignored.)

    rest.addHeader(name: "Content-Type", value: "multipart/form-data")

    // Provide the content for each part of the request...

    // First the JSON attributes.  Use "0" for the root folder.
    //   {"name":"penguins.jpg", "parent":{"id":"0"}}
    let jsonAttr = CkoJsonObject()!
    jsonAttr.updateString(jsonPath: "name", value: "penguins.jpg")
    jsonAttr.updateString(jsonPath: "parent.id", value: "0")

    rest.partSelector = "1"
    rest.addHeader(name: "Content-Disposition", value: "form-data; name=\"attributes\"; ")
    rest.setMultipartBodyString(bodyText: jsonAttr.emit())

    rest.partSelector = "2"
    rest.addHeader(name: "Content-Disposition", value: "form-data; name=\"file\"; filename=\"penguins.jpg\"")
    // "application/octet-stream" can be safely used for any type file..
    rest.addHeader(name: "Content-Type", value: "application/octet-stream")

    // Load the file into a binary data object, and then upload..
    let fileDataObj = CkoBinData()!
    fileDataObj.loadFile(path: "qa_data/jpg/penguins.jpg")
    rest.setMultipartBodyBd(bodyData: fileDataObj)

    // Restore the PartSelector to "0" (for safety, in case something else sends another request on this object)
    rest.partSelector = "0"

    // Send the multipart/form-data request, which uploads the file contained in fileDataObj
    var responseBody: String? = rest.fullRequestMultipart(httpVerb: "POST", uriPath: "/api/2.0/files/content")
    if rest.lastMethodSuccess != true {
        print("\(rest.lastErrorText!)")
        return
    }

    // A 201 is received for a successful upload
    if rest.responseStatusCode.intValue != 201 {
        print("Box.com upload failed.")
        print("Request header:")
        print("\(rest.lastRequestHeader!)")
        print("---")
        print("Response status code = \(rest.responseStatusCode.intValue)")
        print("Response body:")
        print("\(responseBody!)")
        return
    }

    print("File uploaded.")

}