Handling file URLs

更新时间:
复制 MD 格式

Alibaba Cloud Vision Intelligence Platform services require a file URL to access and process your files. This topic explains how to obtain a URL for a local file or an existing web link.

Background information

API response time depends on file download speed. To prevent timeouts, we recommend storing your files in OSS.

Note

For questions about API integration, using Vision AI capabilities, or troubleshooting, join our DingTalk group (23109592).

Scenario 1: OSS files in Shanghai

  1. Log in to the OSS console.

  2. Create a bucket.

    When creating a bucket, select the same region as the Alibaba Cloud Vision Intelligence Platform service. All services are currently located in the China (Shanghai) region.

    Note

    If your OSS bucket is not in the China (Shanghai) region, see Scenario 2: Local files and non-Shanghai OSS files.

  3. Upload a local file to OSS.

    For more information, see Upload files.

  4. View the file URL.

    In the file list, click Details next to your file to view and copy its URL.

Scenario 2: Local files and non-Shanghai OSS files

For local files or OSS files outside the China (Shanghai) region, use an SDK to make API calls.

Configure environment variables

Set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • The AccessKey pair for your Alibaba Cloud account grants full API access. For improved security, we recommend using a RAM user for API calls and routine O&M. For more information, see Create a RAM user.

  • Do not hard-code your AccessKey ID or AccessKey Secret in your project. Leaking these credentials will compromise all resources in your account.

  • For Linux and macOS

    1. In IntelliJ IDEA, open the Terminal.

    2. Run the following commands to set the environment variables.

      Replace <access_key_id> and <access_key_secret> with the AccessKey pair of your RAM user. For more information about permissions, see Use RAM policies to control access.

      export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • For Windows

    Create the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables, using your AccessKey ID and AccessKey Secret as the respective values. Restart Windows for the changes to take effect. The following steps use Windows 10 as an example.

    1. Open File Explorer, right-click This PC, and select Properties.

    2. In the right-side navigation pane, click Advanced system settings.

    3. In the System Properties dialog box, on the Advanced tab, click Environment Variables.

    4. In the Environment Variables dialog box, click New....

    5. In the New System Variable dialog box, create the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET variables and set their values to your AccessKey ID and AccessKey Secret, respectively.

    6. Restart Windows for the settings to take effect.

Method 1 (Recommended)

Use the latest SDK for your language. The latest SDKs can process local files and files from any OSS region. To do so, you must use a request object like xxxAdvanceRequest to pass the file as a stream through a parameter such as ImageURLObject. The exact parameter name may vary depending on the programming language. Refer to the API documentation for the specific operation you are calling for the exact request parameter name. For details, see the SDK references for each language below. 

Method 2

If you cannot use the latest SDK, you can use viapi-utils to generate a temporary URL. The following sections provide language-specific instructions.

Important

This method uploads files to a shared OSS bucket for temporary storage and is intended for API testing only. This method is not recommended for production environments, is not covered by an SLA, and is not suitable for paid users. Files are retained for one day. All users share a total throughput of 10,000 QPS. During peak hours, heavy usage by other users may cause your API calls to fail due to OSS storage contention.

For example, if you purchase a 100 QPS plan for an API but use this free bucket, your calls will still be limited by the shared 10,000 QPS throughput. You may not be able to reach your purchased 100 QPS limit due to this shared contention.

Java SDK

Install the following Java SDK package. Requires Java 8 or later.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>viapi-utils</artifactId>
    <version>1.0.2</version>
</dependency>

The following code provides an example.

import com.aliyun.com.viapi.FileUtils;
public class Main {
    public static void main(String[] args) throws Exception {
        // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
        // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.      
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");     
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // Scenario 1: Use a local file.
        String file = "/tmp/bankCard.png";
        // Scenario 2: Use any accessible URL.
        // String file = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg";
        FileUtils fileUtils = FileUtils.getInstance(accessKeyId, accessKeySecret);
        String ossUrl = fileUtils.upload(file);
        // The generated URL can be used to call the APIs of Alibaba Cloud Vision Intelligence Platform.
        System.out.println(ossUrl);
    }
}

Python SDK

Install the following Python SDK packages. Requires Python 3 or later.

pip install oss2
pip install aliyun-python-sdk-viapiutils
pip install viapi-utils

The following code provides an example.

from viapi.fileutils import FileUtils
# To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
# If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
# Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.
file_utils = FileUtils(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
# Scenario 1: Use a local file. The first parameter is the file path, the second is the suffix for the generated URL (this does not change the actual file type), and the third parameter (True) indicates local file mode.
# oss_url = file_utils.get_oss_url("/tmp/bankCard.png", "png", True)
# Scenario 2: Use any accessible URL. The first parameter is the URL, the second is the suffix for the generated URL (this does not change the actual file type), and the third parameter (False) indicates non-local file mode.
oss_url = file_utils.get_oss_url("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg", "jpg", False)
# The generated URL can be used to call the APIs of Alibaba Cloud Vision Intelligence Platform.
print(oss_url)

Node.js SDK

We recommend that you use NPM to install the dependency package. Requires Node.js 8.x or later.

npm install @alicloud/viapi-utils@^1.0.0 --save

The following JavaScript code provides an example.

const ViapiUtil = require('@alicloud/viapi-utils');
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.
let accessKeyId =  process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
let accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
// Scenario 1: Use a local file.
let file = "/tmp/bankCard.png";
// Scenario 2: Use any accessible URL.
// let file = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg";
ViapiUtil.default.upload(accessKeyId, accessKeySecret, file)
  .then(function(ossUrl) {
    // The generated URL can be used to call the APIs of Alibaba Cloud Vision Intelligence Platform.
    console.log(ossUrl);
  })
  .catch(function(err) {
    console.log(err);
  });           

The following TypeScript code provides an example.

import ViapiUtil from '@alicloud/viapi-utils';
export default class Client {
  static async main(): Promise<void> {
    // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
    // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
    // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.
    let accessKeyId: string = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
    let accessKeySecret: string = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
    // Scenario 1: Use a local file.
    let file: string = "/tmp/bankCard.png";
    // Scenario 2: Use any accessible URL.
    // let file: string = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg";
    let ossUrl: string = await ViapiUtil.upload(accessKeyId, accessKeySecret, file);
    // The generated URL can be used to call the APIs of Alibaba Cloud Vision Intelligence Platform.
    console.log(ossUrl);
  }
}
Client.main();    

PHP SDK

We recommend that you use Composer to install the dependency package. Requires PHP 5.6 or later. PHP 8 is not currently supported.

composer require alibabacloud/viapi-utils

The following code provides an example.

<?php
namespace Alibabacloud\SDK;
use AlibabaCloud\SDK\ViapiUtils\ViapiUtils;
class Client {
    public static function main() {
        // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
        // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.    
        $accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');      
        $accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
        // Scenario 1: Use a local file.
        // $file = "/tmp/bankCard.png";
        // Scenario 2: Use any accessible URL.
        $file = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg";
        $ossUrl = ViapiUtils::upload($accessKeyId, $accessKeySecret, $file);
        // The generated URL can be used to call the APIs of Alibaba Cloud Vision Intelligence Platform.
        echo $ossUrl;
    }
}
// Import autoload.php.
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Client::main(array_slice($argv, 1));

Go SDK

We recommend that you use Go tools to install the dependency package. Requires Go 1.15.x or later.

go get github.com/alibabacloud-go/viapi-utils/client

The following code provides an example.

package main
import (
    "fmt"
    "github.com/alibabacloud-go/tea/tea"
    "os"
    viapiutil "github.com/alibabacloud-go/viapi-utils/client"
)
func main() {
    // Scenario 1: Use a local file.
    file := tea.String("/tmp/bankCard.png")
    // Scenario 2: Use any accessible URL.
    // file := tea.String("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg")
    // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
    // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
    // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.
    // After a successful upload, the URL of the uploaded file is returned.
    ossUrl, _err := viapiutil.Upload(tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")), tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")), file)
    if _err != nil {
        fmt.Println(_err)
    }
    // The generated URL can be used to call the APIs of Alibaba Cloud Vision Intelligence Platform.
    fmt.Println(*ossUrl)
}

.NET SDK

We recommend that you use NuGet to install the dependency package. Requires .NET Framework 4.5 or .NET Core 2.0 or later.

dotnet add package AlibabaCloud.SDK.VIAPIUtils

The following code provides an example.

using System;
// dotnet add package AlibabaCloud.SDK.VIAPIUtils
using AlibabaCloud.SDK.VIAPI.Utils;
namespace viapitest
{
    class Program
    {
        static void Main(string[] args)
        {
            // Scenario 1: Use a local file.
            // string file = "/tmp/bankCard.png";
            // Scenario 2: Use any accessible URL.
            string file = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg";
            // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
            // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
            // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.
            FileUtils fileobj = FileUtils.getInstance(Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            string ossUrl = fileobj.Upload(file);
            // The generated URL can be used to call the APIs of Alibaba Cloud Vision Intelligence Platform.
            Console.WriteLine(ossUrl);
        }
    }
}

Other languages

If your language is not listed above, you can replicate the viapi-utils logic by following these steps:

  1. Call the GetOssStsToken operation to obtain a temporary OSS STS token. For security, each token should be used only once for the subsequent upload. For more information, see request signature.

    • API action: GetOssStsToken

    • API version: 2020-04-01

    • Endpoint: viapiutils.cn-shanghai.aliyuncs.com

    • No business parameters

    • Response data

    Parameter

    Type

    Example

    Description

    AccessKeyId

    String

    STS.NTT2MimJtnhtStr14rzky****

    The AccessKey ID of the temporary STS token.

    AccessKeySecret

    String

    9VoH2Q5s286TaA9yyfZHqXWezdq5qK4i6auR2Vd5****

    The AccessKey secret of the temporary STS token.

    SecurityToken

    String

    CAIShwN1q6Ft5B2yfSjIr5fh****...

    The security token of the temporary STS token.

  2. Use the temporary OSS STS token to upload the file to the shared OSS bucket. For more information, see OSS SDK examples.

    When you use an OSS STS token to upload files to the official bucket, note the following:

    1. The OSS bucket region is fixed to cn-shanghai.

    2. The OSS bucket name is fixed to viapi-customer-temp.

    3. The upload path prefix must be the AccessKeyId that you used when calling the operation in Step 1.

      For example, if the AccessKeyId you used is LTAxxxxxxxabc, the OSS object path must look like: LTAxxxxxxxabc/<uuid>/test.jpg. To prevent files from overwriting each other, we recommend that you add a <uuid> to the path to ensure uniqueness.

  3. After the upload is complete, you will receive an OSS URL. Use this URL in subsequent API requests.

    The URL path should look similar to the following example:

    http://viapi-customer-temp.oss-cn-shanghai.aliyuncs.com/LTAxxxxxxxabc/<uuid>/test.jpg
    Note

    You cannot open or access this URL directly in a browser. Use it as the file URL parameter when calling the platform's APIs.

This section uses Bank Card Recognition (RecognizeBankCard) as an example to demonstrate the viapi-utils logic in different scenarios. To call other APIs, modify the code as indicated in the comments.