NextCloud Python上传文件和分享链接

上传文件

import requests

def upload_file(file_path, upload_url, username, password):
    # Read the file data
    with open(file_path, 'rb') as file:
        file_data = file.read()

    # Set the headers and authentication
    headers = {
        'OCS-APIRequest': 'true',
    }
    auth = (username, password)

    # Upload the file
    response = requests.post(upload_url, headers=headers, auth=auth, data=file_data)

    # Check the response status
    if response.status_code == 200:
        print("File uploaded successfully.")
    else:
        print("File upload failed. Status code:", response.status_code)

# Example usage
file_path = '/path/to/file.txt'
upload_url = 'https://your-nextcloud-instance/remote.php/dav/files/USERNAME/destination_folder/file.txt'
username = 'your_username'
password = 'your_password'

upload_file(file_path, upload_url, username, password)

分享链接

import requests
import json

def generate_download_link(file_path, share_url, username, password):
    # Set the headers and authentication
    headers = {
        'OCS-APIRequest': 'true',
        'Content-Type': 'application/json',
    }
    auth = (username, password)

    # Share the file
    share_data = {
        'path': file_path,
        'shareType': 3,  # Share with public link
        'permissions': 1,  # Read-only permissions
    }
    response = requests.post(share_url, headers=headers, auth=auth, data=json.dumps(share_data))

    # Check the response status
    if response.status_code == 200:
        share_response = response.json()
        download_link = share_response['ocs']['data']['url']
        print("Download link:", download_link)
    else:
        print("Sharing file failed. Status code:", response.status_code)

# Example usage
file_path = '/path/to/file.txt'
share_url = 'https://your-nextcloud-instance/ocs/v2.php/apps/files_sharing/api/v1/shares'
username = 'your_username'
password = 'your_password'

generate_download_link(file_path, share_url, username, password)

你可能感兴趣的:(python,nextcloud)