Question

Upload file using REST

How can I consume a service to send a file? I’m using dart with the following code, and I only get 403.

Can someone help me?

final file = File('./README.md');
    const accessKey = 'afdda';
    const secretKey = 'afda';
    final spaceName = 'fada';
    final region = 'nyc3';
    final fileName = 'README.md';

    final date = DateTime.now().toUtc().toIso8601String();
    final contentType = ContentType.parse('text/plain');
    final acl = 'private';
    final contentLength = await file.length();

    final stringToSign =
        'POST\n$contentType\n$date\nx-amz-acl:$acl\n/$spaceName/$fileName';
    final hmacSha1 = Hmac(sha1, utf8.encode(secretKey));
    final signature =
        base64Url.encode(hmacSha1.convert(utf8.encode(stringToSign)).bytes);

    print('$spaceName.$region.digitaloceanspaces.com/$fileName');
    final url =
        Uri.https('$spaceName.$region.digitaloceanspaces.com', '/$fileName');

    final request = await HttpClient().postUrl(url)
      ..headers.add('Date', date)
      ..headers.add('Content-Type', contentType.toString())
      ..headers.add('Content-Length', contentLength.toString())
      ..headers.add('Authorization', 'AWS $accessKey:$signature')
      ..headers.add('x-amz-acl', acl)
      ..add(await file.readAsBytes());

    final response = await request.close();

    print('Response status code: ${response.statusCode}');
    print('Response body:');
    await response.transform(utf8.decoder).forEach(print);

Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Bobby Iliev
Site Moderator
Site Moderator badge
March 12, 2023

Hi there,

As far as I can see the host header is missing:

Host: The target host for the request (e.g. ${REGION}.digitaloceanspaces.com or ${BUCKET}.${REGION}.digitaloceanspaces.com).

For more information about the common headers, you could take a look at the docs here:

https://docs.digitalocean.com/reference/api/spaces-api/#common-headers

On another note, I would personally suggest using the s3 client instead:

// Step 1: Import the S3Client object and all necessary SDK commands.
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';


// Step 2: The s3Client function validates your request and directs it to your Space's specified endpoint using the AWS SDK.
const s3Client = new S3Client({
    endpoint: "https://nyc3.digitaloceanspaces.com", // Find your endpoint in the control panel, under Settings. Prepend "https://".
    forcePathStyle: false, // Configures to use subdomain/virtual calling format.
    region: "us-east-1", // Must be "us-east-1" when creating new Spaces. Otherwise, use the region in your endpoint (e.g. nyc3).
    credentials: {
      accessKeyId: "C58A976M583E23R1O00N", // Access key pair. You can create access key pairs using the control panel or API.
      secretAccessKey: process.env.SPACES_SECRET // Secret access key defined through an environment variable.
    }
});


// Step 3: Define the parameters for the object you want to upload.
const params = {
  Bucket: "example-space", // The path to the directory you want to upload the object to, starting with your Space name.
  Key: "folder-path/hello-world.txt", // Object key, referenced whenever you want to access this file later.
  Body: "Hello, World!", // The object's contents. This variable is an object, not a string.
  ACL: "private", // Defines ACL permissions, such as private or public.
  Metadata: { // Defines metadata tags.
    "x-amz-meta-my-key": "your-value"
  }
};


// Step 4: Define a function that uploads your object using SDK's PutObjectCommand object and catches any errors.
const uploadObject = async () => {
  try {
    const data = await s3Client.send(new PutObjectCommand(params));
    console.log(
      "Successfully uploaded object: " +
        params.Bucket +
        "/" +
        params.Key
    );
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};

// Step 5: Call the uploadObject function.
uploadObject();

Hope that this helps!

Best,

Bobby

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

card icon
Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Sign up
card icon
Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Learn more
card icon
Become a contributor

You get paid; we donate to tech nonprofits.

Learn more
Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether you’re running one virtual machine or ten thousand.

Learn more ->
DigitalOcean Cloud Control Panel
Get started for free

Enter your email to get $200 in credit for your first 60 days with DigitalOcean.

New accounts only. By submitting your email you agree to our Privacy Policy.

© 2023 DigitalOcean, LLC.