Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Working with Microsoft OneDrive folders and files

Your apps can use the Live Connect APIs to create, read, update, and delete a Microsoft OneDrive user's folders and files.

Note  In this context, a file represents a file of any supported format, including a photo, video, or audio. A folder can contain child folders and files. (An album is a special type of folder; for more info, see Albums, photos, videos, audio, and tags.)

Your apps can also use the APIs to get a link to an uploaded file. Then you can share this link with others so that they can access the file directly.

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples. To request the required scopes, see the code patterns in Obtaining user consent.

Reading folder properties

To get info about a folder, use code like this. The wl.skydrive scope is required.

[JavaScript and HTML for Windows Store apps]


function readFolderProperties_onClick() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!164",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = 
                        "Folder properties: name = " + response.name + ", ID = " + response.id;                
                }, 
                function (responseFailed) {
                    document.getElementById("infoArea").innerText = 
                        "Error reading folder properties: " + responseFailed.error.message;
                }
            );
        }, 
        function (responseFailed) {
            document.getElementById("infoArea").innerText = 
                "Error signing in: " + responseFailed.error_description;
        }
    );
}


[C# for Windows Store apps and Windows Phone apps]


private async void btnReadFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!126");
        dynamic result = operationResult.Result;
        infoTextBlock.Text = "Folder name: " + result.name + ", ID: " + result.id;
    }
    catch (LiveConnectException exception)
    {
        infoTextBlock.Text = "Error getting folder info: " + exception.Message;
    }
}


[Objective-C for iOS]


- (void) getFolderInfo
{
    NSString *folderId = @"folder.2e82e8a5445fe036";
    [self.liveClient getWithPath:folderId 
                        delegate:self 
                       userState:@"get folder"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{    
    if ([operation.userState isEqual:@"get folder"]) {
        self.folderIdLabel.text = [operation.result objectForKey:@"id"];
        self.folderNameLabel.text = [operation.result objectForKey:@"name"];   
        self.folderUploadPathLabel.text = [operation.result objectForKey:@"upload_location"]; 
        self.folderLinkLabel.text = [operation.result objectForKey:@"link"];          
        self.folderTypeLabel.text = [operation.result objectForKey:@"type"];   
    };
}

- (void) liveOperationFailed:(NSError *)error 
                   operation:(LiveOperation *)operation
{    
    if ([operation.userState isEqual:@"get folder"]) {
        self.statusLabel.text = @"The request to read the OneDrive folder information failed.";
    };
}


[Java for Android]


public void readFolder() {
    client.getAsync("folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Folder ID = " + result.optString("id") + 
                ", name = " + result.optString("name"));
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error reading folder: " + exception.getMessage());
        }
    });
}


[REST]

GET https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114?access_token=ACCESS_TOKEN

In the preceding code, change the folder ID to this:

  • A different folder ID, to get info about another folder.
  • FOLDER_ID/files, where FOLDER_ID represents a valid folder ID, to get a list of all items in a folder. Your code can check to see whether any of these items has its type structure set to folder. Then your code can make another call that uses the item's folder ID to get that folder's info, too.

You can also do this:

  • Get info about a user's top-level folder in the OneDrive directory. To do this, replace the folder ID with me/skydrive (or USER_ID/skydrive).
  • Get info about certain folders by using their friendly names. To do this, use me/skydrive/FRIENDLY_FOLDER_NAME or USER_ID/skydrive/FRIENDLY_FOLDER_NAME, where me represents the current consenting user, USER_ID represents the consenting user's ID, and FRIENDLY_FOLDER_NAME represents an allowed friendly folder name such as my_documents (which represents the Documents folder). For more info, see "Using friendly names to access certain OneDrive folders" in Common tasks in accessing OneDrive from your app.
  • Get only certain types of items by using the filter parameter in the preceding code and specifying the item type: all (default), photos, videos, audio, folders, or albums. For example, to get only photos, use FOLDER_ID/files?filter=photos.
  • Get a limited number of items by using the limit parameter in the preceding code to specify the number of items to get. For example, to get the first two items, use FOLDER_ID/files?limit=2.
  • Specify the first item to get by setting the offset parameter in the preceding code to the index of the first item that you want to get. For example, to get two items starting with the third item, use FOLDER_ID/files?limit=2&offset=3.

    Note  In the JavaScript Object Notation (JSON)-formatted object that's returned, you can look in the paging object for the previous and next structures, if they apply, to get the offset and limit parameter values of the previous and next entries, if they exist.

  • Set the items' sort criteria by using the sort_by parameter in the preceding code to specify the following criteria: updated, name, size, or default. For example, to sort the items by name, use FOLDER_ID/files?sort_by=name.
  • Set the items' sort order by using the sort_order parameter in the preceding code to specify the order: ascending or descending. For example, to sort the items in descending order, use FOLDER_ID/files?sort_order=descending.

Top

Deleting folders

To remove a folder, use code like this. The wl.skydrive_update scope is required.

[JavaScript and HTML for Windows Store apps]


function deleteFolder_onClick() {
    WL.login({
        scope: "wl.skydrive_update" 
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!164",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Deleted folder";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                } 
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}


[C# for Windows Store apps and Windows Phone apps]


private async void btnDeleteFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!147");
        this.infoTextBlock.Text = "Folder deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting folder: " + exception.Message;
    }
}


[Objective-C for iOS]


-(void) deleteFolder
{
    [self.liveClient deleteWithPath:@"folder.95d463b9efcca0e1.95D463B9EFCCA0E1!108" 
                           delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!" 
                                                    message:@"Folder deleted successfully"
                                                   delegate:self 
                                          cancelButtonTitle:@"Ok" 
                                          otherButtonTitles:nil, 
                          nil];
    [alert show];
    [alert release];
}


[Java for Android]


public void deleteFile() {
    final String fileId = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125";
    client.deleteAsync(fileId, new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error deleting file: " + exception.getMessage());
           }
           public void onComplete(LiveOperation operation) {
            resultTextView.setText("File deleted.");
           }
       });
    
}


[REST]

DELETE https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114?access_token=ACCESS_TOKEN

In the preceding code, change the folder ID to the folder ID (or, in certain cases, the friendly name) of the folder that you want to remove.

Top

Creating folders

To add a new folder, use code like this. The wl.skydrive_update scope is required.

[JavaScript and HTML for Windows Store apps]


function createFolder_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "me/skydrive",
                method: "POST",
                body: {
                    "name": "This is a new folder",
                    "description": "A new folder"
                } 
            }).then(
                function(response) {
                    document.getElementById("infoArea").innerText = 
                        "Created folder. Name: " + response.name + ", ID: " + response.id;
                }, 
                function (responseFailed) {
                    document.getElementById("infoArea").innerText = 
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText = 
                "Error signing in: " + responseFailed.error_description;
        }
    );
}


[C# for Windows Store apps and Windows Phone apps]


private async void btnCreateFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var folderData = new Dictionary<string, object>();
        folderData.Add("name", "A brand new folder was created");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PostAsync("me/skydrive", folderData);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Created folder:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error creating folder: " + exception.Message;
    }
}


[Objective-C for iOS]


-(void) createFolder
{
    NSDictionary * newFolder = [[NSDictionary dictionaryWithObjectsAndKeys:
                                 @"Vacation Pics",@"name",
                                 @"Family vacation",@"description",
                                 @"folder",@"type",
                                 nil] retain];
    [self.liveClient postWithPath:@"me/skydrive" 
                         dictBody:newFolder
                         delegate:self];
    [newFolder release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *folderId = [operation.result objectForKey:@"id"];
    NSString *folderName = [operation.result objectForKey:@"name"];
    NSString *folderDescription = [operation.result objectForKey:@"description"];
    NSString *folderLink = [operation.result objectForKey:@"link"];
    NSString *folderType = [operation.result objectForKey:@"type"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"Folder Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tLink. %@\n"
                              @"\tType. %@\n"
                              , folderId, 
                              folderName, 
                              folderDescription, 
                              folderLink,
                              folderType];
}


[Java for Android]


public void createFolder() {
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error creating folder: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Folder created:\n" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }), 
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "MyBrandNewFolder");
                    body.put("description", "My brand new folder");
                       client.postAsync("me/skydrive", body, opListener);    
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error building folder: " + ex.getMessage());
                }
               }
        }
    ); 
}


[REST]

POST https://apis.live.net/v5.0/me/skydrive

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example folder"
}

In the preceding code, you can change me/skydrive to the folder ID (or, in certain cases, the friendly name) of the folder in which the new folder will be created.

For details about the minimum required and optional structures that your app must provide to use POST, see the "Folder object" section in REST reference.

Top

Updating folder properties

To change info for an existing folder, use code like this. The wl.skydrive_update scope is required.

[JavaScript and HTML for Windows Store apps]


function updateFolderProperties_onClick() {
    WL.login({
        scope: "wl.skydrive_update" 
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!164",
                method: "PUT",
                body: {
                    name: "A different folder name"
                } 
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = 
                        "Updated folder. Name: " + response.name + ", ID: " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                         "Error calling API: " + responseFailed.error.message;
                } 
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}


[C# for Windows Store apps and Windows Phone apps]


private async void btnUpdateFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var folderData = new Dictionary<string, object>();
        folderData.Add("name", "Wildlife Pictures 5");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PutAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!126", folderData);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Folder updated: " + result.name;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error updating folder: " + exception.Message;
    }
}


[Objective-C for iOS]


-(void) updateFolder
{
    NSDictionary * updatedFolder = [[NSDictionary dictionaryWithObjectsAndKeys:
                                     @"Family vacation in the snow",@"description",
                                     nil] retain];
    [self.liveClient putWithPath:@"folder.95d463b9efcca0e1.95D463B9EFCCA0E1!112" 
                        dictBody:updatedFolder
                        delegate:self];
    [updatedFolder release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!" 
                                                    message:@"Album updated successfully"
                                                   delegate:self 
                                          cancelButtonTitle:@"Ok" 
                                          otherButtonTitles:nil, 
                          nil];
    [alert show];
    [alert release];
}


[Java for Android]


public void updateFolder() {
    final String folderId = "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error updating folder: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Folder updated:\n" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }), 
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "MyFolderIsUpdated");
                    body.put("description", "My folder is updated");
                    client.putAsync(folderId, body, opListener);    
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error updating folder: " + ex.getMessage());
                }
            }
        }
    );  
}


[REST]

PUT https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example folder has changed"
}

In the preceding code, change the folder ID to the folder ID (or, in certain cases, the friendly name) of the folder that you want to change.

For details about the minimum required and optional structures that your app must provide to use PUT, see the "Folder object" section in REST reference.

Top

Reading file properties

To get info about a file, photo, video, or audio, use code like this. The wl.skydrive scope is required.

[JavaScript and HTML for Windows Store apps]


function readFileProperties_onClick() {
    WL.login({ 
        scope: "wl.skydrive" 
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!152",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = 
                        "File properties: name = " + response.name + ", ID = " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                } 
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}


[C# for Windows Store apps and Windows Phone apps]


private async void btnReadFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129");
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "File name:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting file info: " + exception.Message;
    }
}


[Objective-C for iOS]


-(void) getFileProperties
{
    [self.liveClient getWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113" 
                        delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *fileId = [operation.result objectForKey:@"id"];
    NSString *fileName = [operation.result objectForKey:@"name"];
    NSString *fileDescription = [operation.result objectForKey:@"description"];
    NSString *fileSize = [operation.result objectForKey:@"size"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"File Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tSize. %@\n"
                              , fileId, 
                              fileName, 
                              fileDescription, 
                              fileSize];
}


[Java for Android]


public void readFile() {
    String fileId =  "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!141";
       client.getAsync(fileId, new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error reading file: " + exception.getMessage());
           }
           public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "File info:" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       });
}


[REST]

GET https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126?access_token=ACCESS_TOKEN

In the preceding code, change the file ID to a different file ID, photo ID, video ID, or audio ID to get info about a different file, photo, video, or audio.

Top

Updating file properties

To change info about a file, photo, video, or audio, use code like this. The wl.skydrive_update scope is required.

[JavaScript and HTML for Windows Store apps]


function updateFileProperties_onClick() {
    WL.login({ 
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!152",
                method: "PUT",
                body: {
                    name: "AnotherOneNoteNotebook"
                } 
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = 
                        "Updated file properties. Name: " + response.name + ", ID: " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                } 
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Login error.";
        }
    );
}


[C# for Windows Store apps and Windows Phone apps]


private async void btnUpdateFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var fileData = new Dictionary<string, object>();
        fileData.Add("name", "Tulips20.jpg");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PutAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129", fileData);
        this.infoTextBlock.Text = "File renamed.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error renaming file: " + exception.Message;
    }
}


[Objective-C for iOS]


-(void) updateFileProperty
{
    NSDictionary * updatedFile = [[NSDictionary dictionaryWithObjectsAndKeys:
                                   @"Having fun at the beach",@"description",
                                   nil] retain];
    [self.liveClient putWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113" 
                        dictBody:updatedFile
                        delegate:self];
    [updatedFile release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!" 
                                                    message:@"File updated successfully"
                                                   delegate:self 
                                          cancelButtonTitle:@"Ok" 
                                          otherButtonTitles:nil, 
                          nil];
    [alert show];
    [alert release];
}


[Java for Android]


public void updateFile() {
    final String fileId = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!141";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error updating file: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "File updated:" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }), 
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "weather.txt");
                    body.put("description", "Local weather");
                       client.putAsync(fileId, body, opListener);    
                }
                catch(JSONException ex){
                    resultTextView.setText("Error signing in: " + ex.getMessage());
                }
               }
        }
    );     
}


[REST]

PUT https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "MyNewFileName.doc"
}

In the preceding code, change the file ID to a different file ID, photo ID, video ID, or audio ID to change info about a different file, photo, video, or audio.

For details about the minimum required and optional structures that your app must provide to use PUT for a photo, video, or audio, see the "Audio object", "Photo object", or "Video object" section in REST reference. For corresponding details regarding any other file type, see the "File object" section in REST reference.

Top

Downloading files

How to get the contents of a file, photo, video, or audio depends on your app type. The wl.skydrive scope is required.

[JavaScript and HTML for Windows Store apps]

For Windows Store apps using JavaScript, use code like this.


function downloadFile_onClick() {
    var picker = setupSavePicker();
    picker.pickSaveFileAsync().then(
        function (file) {
            if (file && (file instanceof Windows.Storage.StorageFile)) {
                WL.login({
                    scope: "wl.skydrive"
                }).then(
                    function (response) {
                        WL.backgroundDownload({
                            path: "file.8c8ce076ca27823f.8C8CE076CA27823F!129/picture?type=thumbnail",
                            file_output: file
                        }).then(
                            function (response) {
                                document.getElementById("infoLabel").innerText = "Downloaded file.";
                            },
                            function (responseFailed) {
                                document.getElementById("infoLabel").innerText =
                                "Error calling API: " + responseFailed.error.message;
                            }
                        );
                    },
                    function (responseFailed) {
                        document.getElementById("infoLabel").innerText =
                            "Error signing in: " + responseFailed.error.message;
                    }
                );
            }
            else {
                document.getElementById("infoLabel").innerText = "Cannot download file.";
            }
        },
        function (fileFailed) {
            document.getElementById("infoLabel").innerText = "Cannot download file.";
        }
    );
}

function setupSavePicker() {
    var savepicker = new Windows.Storage.Pickers.FileSavePicker();
    savepicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
    savepicker.fileTypeChoices.insert("Picture", [".jpg"]);
    return savepicker;
}


[C#]

For Windows Store apps using C#, use code like this.


private System.Threading.CancellationTokenSource ctsDownload;

private async void btnDownloadFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var picker = new Windows.Storage.Pickers.FileSavePicker();
        picker.SuggestedFileName = "MyDownloadedPicutre.jpg";
        picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads;
        picker.FileTypeChoices.Add("Picture", new List<string>(new string[] { ".jpg" }));
        StorageFile file = await picker.PickSaveFileAsync();
        if (file != null)
        {
            this.progressBar.Value = 0;
            var progressHandler = new Progress<LiveOperationProgress>(
                (progress) => { this.progressBar.Value = progress.ProgressPercentage; });
            this.ctsDownload = new System.Threading.CancellationTokenSource();
            LiveConnectClient liveClient = new LiveConnectClient(this.session);
            await liveClient.BackgroundDownloadAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!161", file, 
                this.ctsDownload.Token, progressHandler);
            this.infoTextBlock.Text = "Download completed.";
        }
    }
    catch (System.Threading.Tasks.TaskCanceledException)
    {
        this.infoTextBlock.Text = "Download cancelled.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting file contents: " + exception.Message;
    }
}

private void btnCancelDownload_Click(object sender, RoutedEventArgs e)
{
    if (this.ctsDownload != null)
    {
        this.ctsDownload.Cancel();
    }
}


Note  For Windows Store apps using C#, the LiveConnectClient.BackgroundDownloadAsync method uses the background transfer service provided by Windows 8. For details, see Transferring a file from a network resource and Windows.Networking.BackgroundTransfer namespace.

For Windows Phone apps, use code like this.


private void btnDownloadFile_Begin(object sender, RoutedEventArgs e)
{
    if (session == null)
    {
        infoTextBlock.Text = "You must sign in first.";
        return;
    }
    try
    {
        LiveConnectClient client = new LiveConnectClient(session);
        var downloadOperationResult = await client.DownloadAsync("file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/picture?type=thumbnail");
        
        using (Stream downloadStream = downloadOperationResult.Stream)
        {
            if (downloadStream != null)
            {
                var imgSource = new BitmapImage();
                imgSource.SetSource(downloadStream);

                // imageFrame is a user-defined Image control.
                this.imageFrame.Source = imgSource;
                this.imageFrame.Visibility = Visibility.Visible;
            }
        }
    }
    catch (LiveConnectException ex)
    {
        infoTextBlock.Text = "Error downloading image: " + ex.Message;
    }
}


Tip  

For Windows Phone 7.5 apps, you can download files even if the app that started the download is suspended or quits. Here's how.

  1. In the code that initializes the LiveConnectClient variable, declare handlers for the LiveConnectClient.BackgroundDownloadCompleted event. (Optionally, you can also handle the LiveConnectClient class's BackgroundDownloadProgressChanged, BackgroundUploadCompleted, and BackgroundUploadProgressChanged events if you want to check the progress of a background file download, do something after a file has been uploaded, or check the progress of a background file upload.) Then call the LiveConnectClient.AttachPendingTransfers method, which checks for pending background file transfers that were started in a previous instance of the app. Here's the code.
    
    private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
    {
        if (e.Status == LiveConnectSessionStatus.Connected)
        {
            session = e.Session;
            client = new LiveConnectClient(session);
            client.BackgroundDownloadProgressChanged +=
                new EventHandler<LiveDownloadProgressChangedEventArgs>(OnBackgroundDownloadProgressChanged);
            client.BackgroundDownloadCompleted +=
                new EventHandler<LiveOperationCompletedEventArgs>(OnBackgroundDownloadCompleted);
            client.BackgroundUploadProgressChanged +=
                new EventHandler<LiveUploadProgressChangedEventArgs>(OnBackgroundUploadProgressChanged);
            client.BackgroundUploadCompleted +=
                new EventHandler<LiveOperationCompletedEventArgs>(OnBackgroundUploadCompleted);
            client.AttachPendingTransfers();
            infoTextBlock.Text = "Signed in.";
        }
        else
        {
            infoTextBlock.Text = "Not signed in.";
            client = null;
        }
    }
    
    
    
  2. Initiate the background file download and implement event handlers for the BackgroundDownloadCompleted event (and, optionally, the BackgroundDownloadProgressChanged event), like this.
    
    private void StartBackgroundDownload(object sender, RoutedEventArgs e)
    {
        client.BackgroundDownloadAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!161",
            new Uri("/shared/transfers/TheNumber5.jpg", UriKind.RelativeOrAbsolute), "TheNumber5Download");
    }
    
    void OnBackgroundDownloadProgressChanged(object sender, LiveDownloadProgressChangedEventArgs e)
    {
        if (e.UserState.ToString() == "TheNumber5Download")
        {
            infoTextBlock.Text = e.UserState.ToString() + ": " + e.BytesReceived + " of " + 
                e.TotalBytesToReceive + " bytes downloaded (" + e.ProgressPercentage + "%)";
        }
    }
    
    void OnBackgroundDownloadCompleted(object sender, LiveOperationCompletedEventArgs e)
    {
        if (e.UserState.ToString() == "TheNumber5Download")
        {
            if (e.Error == null)
            {
                infoTextBlock.Text = "Download completed.";
            }
            else
            {
                infoTextBlock.Text = "Error downloading file: " + e.Error.ToString();
            }
        }
    }
    
    
    

[Objective-C for iOS]


-(void) downloadFile
{
    [self.liveClient downloadFromPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113/content" 
                             delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    LiveDownloadOperation * downloadOperation = (LiveDownloadOperation *)operation;
    UIImage *downloadedPicture = [UIImage imageWithData:downloadOperation.data];
    imageView.image = downloadedPicture;
}


[Java for Android]


public void downloadFile() {
    String file = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/picture?type=thumbnail";
    client.downloadAsync(file, new LiveDownloadOperationListener() {
        public void onDownloadCompleted(LiveDownloadOperation operation)
        {
            try {
                resultTextView.setText("Picture downloaded.");
                InputStream input =  operation.getStream();
                Bitmap bMap = BitmapFactory.decodeStream(input);
                picture.setImageBitmap(bMap);
                input.close();                    
            }
            catch(java.io.IOException ex) {
                resultTextView.setText("Error downloading picture: " + ex.getMessage());
            }
        }
        public void onDownloadFailed(LiveOperationException exception, LiveDownloadOperation operation)
        {
            resultTextView.setText(exception.getMessage());
        }
        public void onDownloadProgress(int totalBytes, int bytesRemaining, LiveDownloadOperation operation)
        {
            resultTextView.setText("Downloading picture... " + bytesRemaining + " bytes downloaded " +
                "(" + (bytesRemaining / totalBytes) * 100 + "%)");
        }
    });
}


[REST]

For Representational State Transfer (REST), use the REST code in the preceding Reading file properties section, but insert /content after the file ID, photo ID, video ID, or audio ID, for example, FILE_ID/content.

Tip  You can instruct the user's web browser to prompt the user to save the file that's downloading instead of having the browser try to download and display the file directly in its own window. To do this, add the download=true query-string parameter after /content (for example, FILE_ID/content?download=true). This call adds the Content-Disposition: attachment header to the response.

To get a download link to the contents of a file, photo, video, or audio, use the REST code in the preceding Reading file properties section, but insert /content?suppress_redirects=true after the file ID, photo ID, video ID, or audio ID, for example, FILE_ID/content?suppress_redirects=true.

[JavaScript and HTML for Windows Store apps]

For client-side websites and scripts that use JavaScript, use code like this.


function downloadFile() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.download({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/content"
            }).then(
                function (response) {
                    // Will not be called for web apps.
                },
                function (responseFailed) {
                    document.getElementById("info").innerText =
                        "Error downloading file: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error signing in: " + responseFailed.error.message;
        }
    );
}


Tip  Instead of hard-coding the file ID, your code can prompt the signed-in user to dynamically select the file (or even multiple files) to download from his or her OneDrive storage location. For more info, see OneDrive file picker for web apps.

To get a download link to the contents of a file, photo, video, or audio, use the JavaScript code in the preceding Reading file properties section, but insert /content?suppress_redirects=true after the file ID, photo ID, video ID, or audio ID—for example, FILE_ID/content?suppress_redirects=true.

Top

Uploading files

How to add contents for a file, photo, video, or audio depends on your app type. The wl.skydrive_update scope is required.

[JavaScript and HTML]

For client-side websites and scripts that use JavaScript, use code like this.


function uploadFile() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.upload({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!170",
                element: "file",
                overwrite: "rename"
            }).then(
                function (response) {
                    document.getElementById("info").innerText =
                        "File uploaded.";
                },
                function (responseFailed) {
                    document.getElementById("info").innerText =
                        "Error uploading file: " + responseFailed.error.message;
                }
            );                    
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error signing in: " + responseFailed.error.message;
        }
    );
}


Tip  Instead of hard-coding the file ID, your code can prompt the signed-in user to dynamically select the file to upload to his or her OneDrive storage location. For more info, see OneDrive file picker for web apps.

For Windows Store apps using JavaScript, use code like this.


function uploadFile_onClick() {
    var picker = setupOpenPicker();
    var filePickOp = picker.pickSingleFileAsync().then(
        function (file) {
            WL.login({
                scope: "wl.skydrive_update"
            }).then(
                function (response) {
                    WL.backgroundUpload({
                        path: "me/skydrive",
                        file_name: file.fileName,
                        file_input: file,
                        overwrite: "rename"
                    }).then(
                       function (response) {
                           document.getElementById("infoLabel").innerText = "Uploaded file.";
                       },
                       function (responseFailed) {
                           document.getElementById("infoLabel").innerText =
                               "Error calling API: " + responseFailed.error.message;
                       }
                    );
                },
                function (responseFailed) {
                    document.getElementById("infoLabel").innerText =
                        "Error signing in: " + responseFailed.error.message;
                }
            );
        },
        function (fileFailed) {
            document.getElementById("infoLabel").innerText = "Cannot upload file.";
        }
    );
}

function setupOpenPicker() {
    var openpicker = new Windows.Storage.Pickers.FileOpenPicker();
    openpicker.fileTypeFilter.replaceAll(["*"]);
    return openpicker;
}


Tip  Before uploading a file, have your app check to make sure that there is enough available OneDrive storage space by making a WL.api GET method call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the OneDrive quota call. For more info, see the "Getting a user's total and remaining OneDrive storage quota" section in Common tasks in accessing Microsoft OneDrive from your app.

[C#]

For Windows Store apps using C#, use code like this.


private System.Threading.CancellationTokenSource ctsUpload;

private async void btnUploadFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var picker = new Windows.Storage.Pickers.FileOpenPicker();
        picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        picker.FileTypeFilter.Add("*");
        Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            this.progressBar.Value = 0;
            var progressHandler = new Progress<LiveOperationProgress>(
                (progress) => { this.progressBar.Value = progress.ProgressPercentage; });
            this.ctsUpload = new System.Threading.CancellationTokenSource();
            LiveConnectClient liveClient = new LiveConnectClient(this.session);
            await liveClient.BackgroundUploadAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!134",
                "MyUploadedPicture.jpg", file, true, this.ctsUpload.Token, progressHandler);
            this.infoTextBlock.Text = "Upload completed.";
        }
    }
    catch (System.Threading.Tasks.TaskCanceledException)
    {
        this.infoTextBlock.Text = "Upload cancelled.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error uploading file: " + exception.Message;
    }
}

private void btnCancelUpload_Click(object sender, RoutedEventArgs e)
{
    if (this.ctsUpload != null)
    {
        this.ctsUpload.Cancel();
    }
}


Tip  Before uploading a file, have your app check to make sure that there is enough available OneDrive storage space by making a LiveConnectClient.GetAsync method call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the OneDrive quota call. For more info, see the "Getting a user's total and remaining OneDrive storage quota" section in Common tasks in accessing Microsoft OneDrive from your app.

Note  For Windows Store apps using C#, the LiveConnectClient.BackgroundUploadAsync method uses the background transfer service provided by Windows 8. For details, see Transferring a file from a network resource and Windows.Networking.BackgroundTransfer namespace.

For Windows Phone apps, use code like this.


private void createFile_Click(object sender, RoutedEventArgs e)
{
    var picker = new PhotoChooserTask();
    picker.Completed += 
        new EventHandler<PhotoResult>(OnPhotoChooserTaskCompleted);
    picker.Show();
}

private void OnPhotoChooserTaskCompleted(object sender, PhotoResult e)
{
    if (e.Error != null)
    {
        this.infoTextBlock.Text = "Error choosing photo: " + e.Error.ToString();
    }
    else
    {
        string[] filePathSegments = e.OriginalFileName.Split('\\');
        string fileName = filePathSegments[filePathSegments.Length - 1];
 
        try
        {
            using (var stream = e.ChosenPhoto)
            {
                LiveOperationResult operationResult = await this.liveClient.UploadAsync(
                    "me/skydrive",
                    fileName,
                    stream,
                    OverwriteOption.Rename);
            }
        }
        catch (LiveConnectException ex)
        {
            this.infoTextBlock.Text = "Error uploading photo: " + ex.Message;
        }

    }
}


Tip  

For Windows Phone 7.5 apps, you can upload files even if the app that started the upload is suspended or quits. Here's how.

  1. In the code that initializes the LiveConnectClient variable, declare handlers for the LiveConnectClient.BackgroundUploadCompleted event. (Optionally, you can also handle the LiveConnectClient class's BackgroundUploadProgressChanged, BackgroundDownloadCompleted, and BackgroundDownloadProgressChanged events if you want to check the progress of a background file upload, do something after a file has downloaded, or check the progress of a background file download.) Then call the LiveConnectClient.AttachPendingTransfers method, which checks for pending background file transfers that were started in a previous instance of the app. Here's the code.
    
    private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
    {
        if (e.Status == LiveConnectSessionStatus.Connected)
        {
            session = e.Session;
            client = new LiveConnectClient(session);
            client.BackgroundDownloadProgressChanged +=
                new EventHandler<LiveDownloadProgressChangedEventArgs>(OnBackgroundDownloadProgressChanged);
            client.BackgroundDownloadCompleted +=
                new EventHandler<LiveOperationCompletedEventArgs>(OnBackgroundDownloadCompleted);
            client.BackgroundUploadProgressChanged +=
                new EventHandler<LiveUploadProgressChangedEventArgs>(OnBackgroundUploadProgressChanged);
            client.BackgroundUploadCompleted +=
                new EventHandler<LiveOperationCompletedEventArgs>(OnBackgroundUploadCompleted);
            client.AttachPendingTransfers();
            infoTextBlock.Text = "Signed in.";
        }
        else
        {
            infoTextBlock.Text = "Not signed in.";
            client = null;
        }
    }
    
    
    
  2. Initiate the background file upload and implement event handlers for the BackgroundUploadCompleted event (and, optionally, the BackgroundUploadProgressChanged event), like this.
    
    private void StartBackgroundUpload(object sender, RoutedEventArgs e)
    {
        client.BackgroundUploadAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!134",
            new Uri("/shared/transfers/TheNumber5.jpg", UriKind.RelativeOrAbsolute), OverwriteOption.Rename, "TheNumber5Upload");
    }
    
    void OnBackgroundUploadProgressChanged(object sender, LiveUploadProgressChangedEventArgs e)
    {
        if (e.UserState.ToString() == "TheNumber5Upload")
        {
            infoTextBlock.Text = e.UserState.ToString() + ": " + e.BytesSent + " of " + 
                e.TotalBytesToSend + " bytes uploaded (" + e.ProgressPercentage + "%)";
        }
    }
    
    void OnBackgroundUploadCompleted(object sender, LiveOperationCompletedEventArgs e)
    {
        if (e.UserState.ToString() == "TheNumber5Upload")
        {
            if (e.Error == null)
            {
                infoTextBlock.Text = "Upload completed.";
            }
            else
            {
                infoTextBlock.Text = "Error uploading file: " + e.Error.ToString();
            }
        }
    }
    
    
    

[Objective-C for iOS]


-(void) uploadFile
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Fire-Phoenix" ofType:@"jpg"];
    NSData *fileToUpload = [[[NSData alloc]initWithContentsOfFile:path] retain];
    [self.liveClient uploadToPath:@"me/skydrive"
                         fileName:@"Favorite pic.jpg" 
                             data:fileToUpload
                         delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *fileId = [operation.result objectForKey:@"id"];
    NSString *fileName = [operation.result objectForKey:@"name"];
    NSString *fileDescription = [operation.result objectForKey:@"description"];
    NSString *fileSize = [operation.result objectForKey:@"size"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"File Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tSize. %@\n"
                              , fileId, 
                              fileName, 
                              fileDescription, 
                              fileSize];
}


Tip  Before uploading a file, have your app check to make sure that there is enough available OneDrive storage space by making a LiveConnectClient getWithPath:delegate:userState method call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the OneDrive quota call. For more info, see the "Getting a user's total and remaining OneDrive storage quota" section in Common tasks in accessing Microsoft OneDrive from your app.

[Java for Android]


public void createFile() {
    final Runnable uploadImage = new Runnable() {
        public void run() {
            final String imageUrl = "http://i.imgur.com/LYZEGB.jpg"; 
            final String fileName = "Vase-Cup.jpg";
            final URL url;
            final URLConnection ucon;
            final InputStream is;
            try {
                url = new URL(imageUrl); 
                ucon = url.openConnection();
                is = ucon.getInputStream();
                client.uploadAsync("me/skydrive", fileName, is, new LiveUploadOperationListener() {
                    public void onUploadFailed(LiveOperationException exception, LiveOperation operation) {
                        resultTextView.setText("Error uploading file: " + exception.getMessage());
                    }
                    public void onUploadCompleted(LiveOperation operation) {
                        resultTextView.setText("File uploaded.");
                        try {
                            is.close();
                        }    
                        catch(IOException ioe) {
                            resultTextView.setText("Error uploading file: " + ioe.getMessage());
                        }
                    }
                    public void onUploadProgress(int totalBytes, int bytesRemaining, LiveOperation operation)
                          {
                              resultTextView.setText("Uploading file... " + bytesRemaining + " bytes remaining " +
                                "(" + (bytesRemaining / totalBytes) * 100 + "%)");
                          }
                });
            }
            catch(IOException ioex) {
                resultTextView.setText("Error uploading file: " + ioex.getMessage());
                return;
            }
            catch(Exception ex)
            {
                resultTextView.setText("Error uploading file: " + ex.getMessage());
                return;
            } 
        }
    };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }), new LiveAuthListener() {
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
        }
          public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
              new Thread(uploadImage).start();
        }
      });   
    
}


Tip  Before uploading a file, have your app check to make sure that there is enough available OneDrive storage space by making a LiveConnectClient.getAsync method call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the OneDrive quota call. For more info, see the "Getting a user's total and remaining OneDrive storage quota" section in Common tasks in accessing Microsoft OneDrive from your app.

If you're using a PUT request, you can use one of these specifiers.

  • me/skydrive/files/FILE_NAME
  • The value of the upload_location structure for the folder to which the file, photo, video, or audio will be uploaded, followed by a forward slash character (/) and the file name.
  • The folder ID of the folder to which the file, photo, video, or audio will be uploaded, followed by /files/ and the file name.
  • If the file already exists from a previous upload operation, the value of the existing file's upload_location structure.
  • If the file already exists from a previous upload operation, the file ID of the file, followed by /content.

For details about the minimum required and optional structures that your app must provide when you use POST or PUT to upload a photo, video, or audio, see the "Audio object", "Photo object", or "Video object" section in REST reference.

For details about the minimum required and optional structures that your app must provide when you use POST or PUT to upload any other file type, see the "File object" section in REST reference.

[REST]

For REST, you can use PUT or POST, depending on your platform's recommended approach.

Important  On platforms that support the PUT request, PUT should be used to upload files to OneDrive when possible to avoid errors that can occur when POST is used.

Here's an example of code that uses PUT.

PUT https://apis.live.net/v5.0/me/skydrive/files/HelloWorld.txt?access_token=ACCESS_TOKEN

Hello, World!

Note  By default, the file, photo, video, or audio with the same name will be overwritten, if it already exists. You can add an overwrite query-string parameter with a value of false to not overwrite the existing file, photo, video, or audio. Or you can add an overwrite query-string parameter of ChooseNewName if you want to upload a duplicate copy of the file but let OneDrive choose a new file name for the uploaded file.

Here's an example of code that uses POST.

POST https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN

Content-Type: multipart/form-data; boundary=A300x

--A300x
Content-Disposition: form-data; name="file"; filename="HelloWorld.txt"
Content-Type: application/octet-stream

Hello, World!
--A300x--

For REST, if you're using POST as shown here, you must format the request as multipart/form-data. You provide the file to upload in a multipart section, while you provide the file name in the Content-Disposition header's filename parameter. For more info, see RFC 2388. Note that only one multipart section is supported in the body of the request.

Also for REST, if you're using POST, you can use any of these.

  • me/skydrive/files
  • FOLDER_ID/files, where FOLDER_ID is the ID of the parent folder.
  • The value of the upload_location structure for the folder to which the file, photo, video, or audio will be uploaded.

You can instruct OneDrive to notify the web browser when the upload finishes. You can also attach a unique identifier to each upload request so that you can identify a particular file if you are uploading multiple files in quick succession. To do this, use a POST multipart/form-data request, like this:

POST https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!110/files?state=MyNewFileState&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.htm&access_token=ACCESS_TOKEN

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="file"; filename="MyNewFile.txt"
Content-Type: text/plain

These are the contents of my new file.
--AaB03x--

In this example, replace the folder ID with your target folder ID; replace the state query-string parameter value with your unique identifier; and replace the redirect_uri parameter with the path to your callback page. Note that the domain portion of the path must match the redirect domain that you specified in the Live Connect app management site for the corresponding client ID.

OneDrive returns HTML-formatted code similar to the following.

<html>
    <head>
        <script type="text/javascript">
            window.location = "http://www.contoso.com/callback.htm#state=MyNewFileState&result=%7B%22id%22%3A%22file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!184%22%2C%22source%22%3A%22http%3A%2F%2Fstorage.live.com%2Fs1pasGKzgXFvuEQCbxGtOyIpboUVH1OCHoRzUJNDDwL0zVoidb0RRrNVk88hUrOEve5OMT7eCkuxPbop7dV9tMJQ-eE8SCQ28vFv9ZgPnDGwQMRm-0FeG3-KEY4HL9dQSw9%2FMyNewFile.txt%3ABinary%2CDefault%2FMyNewFile.txt%22%7D";
        </script>
    </head>
</html>

When decoded, the result response parameter is similar to this.

{
    "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!184",
    "source": "http://storage.live.com/s1pasGKzgXFvuEQCbxGtOyIpboUVH1OCHoRzUJNDDwL0zVoidb0RRrNVk88hUrOEve5OMT7eCkuxPbop7dV9tMJQ-eE8SCQ28vFv9ZgPnDGwQMRm-0FeG3-KEY4HL9dQSw9/MyNewFile.txt:Binary,Default/MyNewFile.txt"
}

Note  By default, the file, photo, video, or audio with the same name will be overwritten, if it already exists. You can add an overwrite  query-string parameter with a value of false to not overwrite the existing file, photo, video, or audio. Or you can add an overwrite query-string parameter of ChooseNewName if you want to upload a duplicate copy of the file but let OneDrive choose a new file name for the uploaded file.

Tip  Before uploading a file, have your app check to make sure that there is enough available OneDrive storage space by making a GET call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the OneDrive quota call. For more info, see the "Getting a user's total and remaining OneDrive storage quota" section in Common tasks in accessing Microsoft OneDrive from your app.

Top

Updating uploaded files

To change contents for an existing file, photo, video, or audio, use the code in the preceding Uploading files section, plus one of the following methods:

  • For JavaScript, use WL.upload.
  • For C# for Windows Store apps, use LiveConnectClient.BackgroundUploadAsync.
  • For C# for Windows Phone, use LiveConnectClient.UploadAsync or LiveConnectClient.BackgroundUpload.
  • For Objective-C, use LiveConnectClient uploadToPath:fileName:data:delegate:userState.
  • For Java, use LiveConnectClient.uploadAsync.
  • For REST, use POST or PUT.

Top

Deleting uploaded files

To remove a file, photo, video, or audio, use code like this. The wl.skydrive_update scope is required.

[JavaScript and HTML for Windows Store apps]


function deleteFile_onClick() {
    WL.login({ 
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!152",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Deleted file.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                } 
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}


[C# for Windows Store apps and Windows Phone apps]


private async void btnDeleteFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!147");
        this.infoTextBlock.Text = "Folder deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting folder: " + exception.Message;
    }
}


[Objective-C for iOS]


-(void) deleteFile
{
    [self.liveClient deleteWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113"
                           delegate:self];    
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!" 
                                                    message:@"File deleted successfully"
                                                   delegate:self 
                                          cancelButtonTitle:@"Ok" 
                                          otherButtonTitles:nil, 
                          nil];
    [alert show];
    [alert release];
}


[Java for Android]


public void deleteFile() {
    final String fileId = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125";
    client.deleteAsync(fileId, new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error deleting file: " + exception.getMessage());
           }
           public void onComplete(LiveOperation operation) {
            resultTextView.setText("File deleted.");
           }
       });
    
}


[REST]

DELETE https://apis.live.net/v5.0/file.b7c3b8f9g3616f6f.B7CB8F9G3626F6!225?access_token=ACCESS_TOKEN

In the preceding code, change the file ID to a different file ID, photo ID, video ID, or audio ID to remove a different file, photo, video, or audio.

Top

Getting links to folders and files

Your apps can get the following types of links to OneDrive folders and files.

  • An embedded link, which is an HTML code snippet that you can insert into a webpage to provide an interactive view of the corresponding file.

    Note  Currently, embedded links are supported only for files owned by the user. To determine whether a given file can be embedded, check to see if the corresponding File object's is_embeddable structure is set to true. Also, some embedded links provide a rich embedding experience, while others provide only an icon and a file name. Rich embedding is supported for the following types of Microsoft PowerPoint, Microsoft Excel, and Microsoft Word files: .doc, .docx, .pdf, .odt, .pot, .potm, .potx, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .xlsb, .xlsm, and .xlsx.

  • A read-only link, which is a link to a read-only version of the folder or file.
  • A read-write link, which is a link to a read-write version of the folder or file.

Important  When your apps request a read-only or read-write link to a file, the URL to that file is the same for either request. When your apps request a read-only link for a file and then later request a read-write link for that same file, read-only permission for that link is revoked. Similarly, when your apps request a read-write link for a file and then later request a read-only link for that same file, read-write permission for that link is revoked.

To get a link to a folder or file, use code like this.

[JavaScript and HTML for Windows Store apps]


function getSharedLink_onClick() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!152/shared_read_link",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = 
                        "Shared link = " + response.link;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                } 
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}


[C# for Windows Store apps and Windows Phone apps]


private async void btnGetLink_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129/shared_read_link");
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Shared read link: " + result.link;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting shared read link: " + exception.Message;
    }
}


[Objective-C for iOS]


-(void) getLinkToFile
{
    [self.liveClient getWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113/shared_read_link"
                        delegate:self
                       userState:@"onClickGetLinkToFileButton"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    self.infoLabel.text = [NSString stringWithFormat: @"Shared read link = %@", [operation.result objectForKey:@"link"]];
}


[Java for Android]


public void getLinkToFile() {
    final String path = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!141/shared_read_link";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error getting link to file: " + exception.getMessage());
           }
           public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text =  "Shared link to file = " + result.optString("link");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive" }), new LiveAuthListener() {
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
        }
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            client.getAsync(path, opListener);
        }
    });        
}


[REST]

GET https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126/shared_read_link?access_token=ACCESS_TOKEN

In the preceding code, change the file ID to the folder ID or file ID that you want a link to. Also, change shared_read_link to one of these.

  • To embed for an embedded link. You get the embed HTML code snippet from the returned JSON-formatted object's embed_html structure value.
  • To shared_read_link for a read-only link. You get the read-only link from the returned JSON-formatted object's link structure value.
  • To shared_edit_link for a read-write link. You get the read-write link from the returned JSON-formatted object's link structure value.

When your app requests a file, photo, video, or audio, the returned object includes a preauthenticated URL as the value of the source attribute. Preauthenticated URLs allow access to a file without the need for additional permissions. Preauthenticated URLs expire and should not be stored or reused later. The following example shows what a preauthenticated URL looks like.

"source": "http://storage.live.com/s1pk0Hsk4twGIbzleNLcqhVhp5yvj9aPLPMHq2GDTRFBeuicbS27Fx5xBnmyy5J4lDSEtdvYm2FxOB0-s8Heb1l6hq3A1E2bJ9qWQ3GdIUTnnG6CHLTBLdCHRPUNAunekX1dnLS49vG-fUV7O8ZvrkiLTubXXFqrT1roxZ1oJjELE/Test.txt:Binary"

Top

Moving folders and files

To move a folder, file, photo, video, or audio, use code like this. The wl.skydrive_update scope is required. For move operations, the source can be anything except the root, and the destination must be the folder to which the item will be moved.

[JavaScript and HTML for Windows Store apps]


function moveFile_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!141",
                method: "MOVE",
                body: {
                    destination: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Item moved.";
                }, 
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Login error: " + responseFailed.error_description;
        }
    );
}


[C# for Windows Store apps and Windows Phone apps]


private async void btnMoveFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient moveFileClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await moveFileClient.MoveAsync("file.9d24497f7fef8f33.9D24497F7FEF8F33!748",
                "folder.9d24497f7fef8f33.9D24497F7FEF8F33!265");
        this.infoTextBlock.Text = "File moved.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error moving file: " + exception.Message;
    }
}


[Objective-C for iOS]


- (void) moveFile
{
    NSString *folderId = @"folder.2e82e8a5445fe036";
    NSString *fileId = @"file.445fe0362e82e8a5";
    [self.liveClient moveFromPath:fileId 
                    toDestination:folderId 
                         delegate:self 
                        userState:@"move a file"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"get folders"]) {
        self.statusLabel.text = @"OneDrive folders are loaded.";
    }
    if ([operation.userState isEqual:@"get folder"]) {
    };
    if ([operation.userState isEqual:@"move a file"]) {
        self.statusLabel.text = [NSString stringWithFormat: @"The file (id: %@) was moved successfully.", operation.path];
    };
}


[Java for Android]


public void moveFile() {
    client.moveAsync("file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!120", 
            "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!145", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            resultTextView.setText("File moved.");
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error moving file: " + exception.getMessage());
        }
    });
}


[REST]

MOVE https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "destination": "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114"
}

Top

Copying files

To copy a file, use code as shown for move operations. The wl.skydrive_update scope is required.

  • For C#, use the LiveConnectClient.CopyAsync method.
  • For Objective-C, use the LiveConnectClient copyFromPath:toDestination:delegate:userState method.
  • For Java, use the LiveConnectClient.copy method.
  • For REST and JavaScript, change MOVE to COPY to copy the item.

Modify the code example that applies to your application as follows:

  • Change the file ID to the file ID or folder ID of the file or folder that you want to move or copy.
  • Change the folder ID to the folder ID of the target folder to which you want to move or copy the source file or folder.

Important  The destination of a move or copy operation must be a folder. Folders themselves cannot be copied. Also, OneDrive storage is structured so that move and copy operations cannot occur between the OneDrive folder hierarchies of different users. For example, even if user A can read user B's files, user A cannot copy or move them to his or her own OneDrive folders.

Top

 

 

Show:
© 2014 Microsoft