使用阿里云视觉智能开放平台服务时,需要传入文件URL,视觉智能平台根据传入的文件URL对文件进行智能处理。本文介绍如何通过本地文件或网络文件链接生成URL。

背景信息

阿里云视觉智能开放平台服务的接口响应时间依赖文件的下载时间,为了保证被检测文件不会下载超时,建议您使用阿里云OSS存储文件。

OSS用户

  1. 登录OSS管理控制台
  2. 创建存储空间
    创建Bucket选择区域时,需要选择与视觉智能开放平台对应服务能力相同的区域,当前视觉智能开放平台各服务支持的区域为华东2(上海)
    说明 如果您的OSS所在地域不是华东2(上海),请参见非上海地域OSS用户(临时文件中转)生成URL。
  3. 上传本地文件到OSS服务。
    具体操作请参见上传文件
  4. 查看文件URL。
    在已上传图片列表中,单击详情查看并复制图片URL。

非上海地域OSS用户(临时文件中转)

对于非OSS用户,或者您的OSS所属地域不是华东2(上海),推荐您使用SDK生成URL。
注意

该方式使用阿里云视觉智能开放平台官方OSS-Bucket作为临时存储,仅为方便用户方便调试接口使用,文件存储有效期为1天。该方式非官方推荐方式,不保证SLA,该方式是所有用户共享总共1万QPS。如果在高峰时段,可能会因为过多用户使用OSS存储,而导致您调用接口失败。所以请勿生产环境使用视觉智能开放平台官方的OSS-Bucket作为存储。此上传接口不推荐付费用户使用

例如,您购买了某个API 100QPS的使用服务,但如果仍使用免费OSS-Bucket,则仍将与其他用户共享总共1万QPS的OSS并发使用量,可能因OSS并发量受限,而无法使用到100QPS的调用量上限。

  • Java SDK
    • 方式一(推荐方式):您可以参见Java(支持本地上传)生成URL。
    • 方式二:如果您使用的API在该方式一中未支持,请按如下步骤执行。
      请安装如下Java SDK包。
      <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>tea-openapi</artifactId>
        <version>0.0.7</version>
      </dependency>
      <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>openplatform20191219</artifactId>
        <version>3.0.1</version>
      </dependency>
      <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>oss-client</artifactId>
        <version>3.0.2</version>
      </dependency>
      <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.7</version>
      </dependency>
      具体代码示例如下。
      package com.aliyun.viapi.demo;
      
      import com.aliyun.fileform.models.FileField;
      import com.aliyun.openplatform20191219.models.AuthorizeFileUploadRequest;
      import com.aliyun.openplatform20191219.models.AuthorizeFileUploadResponse;
      import com.aliyun.oss.models.PostObjectRequest;
      import com.aliyun.tea.TeaConverter;
      import com.aliyun.tea.TeaPair;
      import com.aliyun.teautil.models.RuntimeOptions;
      import org.apache.commons.lang3.StringUtils;
      
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.net.URL;
      import java.net.URLConnection;
      import java.net.URLDecoder;
      import java.util.HashMap;
      import java.util.Map;
      import java.util.concurrent.ConcurrentHashMap;
      
      public class ViapiFileUtilAdvance {
      
          public static void main(String[] args) throws Exception {
              
              String accessKey = "xxx";    //您的AccessKeyID
              String accessKeySecret = "yyy";   //您的AccessKeySecret
              String regionId = "cn-shanghai";
              //String file = "/home/admin/file/1.jpg"; //或者本地上传
              String file = "https://img.alicdn.com/tfs/TB1S0DjC4v1gK0jSZFFXXb0sXXa-692-440.jpg";
              try (InputStream inputStream = buildInputStream(file)) {
                  ViapiFileUtilAdvance fileUtils = ViapiFileUtilAdvance.getInstance(accessKey, accessKeySecret, regionId);
                  String ossTempFileUrl = fileUtils.upload(inputStream);
                  System.out.println(ossTempFileUrl);
              }
          }
      
          public static InputStream buildInputStream(String filePath) throws IOException {
              if (StringUtils.startsWithAny(filePath, new CharSequence[]{"http://", "https://"})) {
                  filePath = URLDecoder.decode(filePath, "UTF-8");
                  URL url = new URL(filePath);
                  URLConnection urlConnection = url.openConnection();
                  return urlConnection.getInputStream();
              } else {
                  File key1 = new File(filePath);
                  return new FileInputStream(key1);
              }
          }
      
          public static synchronized ViapiFileUtilAdvance getInstance(String accessKeyId, String accessKeySecret, String regionId) throws Exception {
              String mapKey = String.format("%s:%s:%s", regionId, accessKeyId, accessKeySecret);
              ViapiFileUtilAdvance fileUtils = _map.get(mapKey);
              if (fileUtils == null) {
                  _map.putIfAbsent(mapKey, new ViapiFileUtilAdvance(accessKeyId, accessKeySecret, regionId));
                  fileUtils = _map.get(mapKey);
              }
              return fileUtils;
          }
      
      
          private ViapiFileUtilAdvance(String accessKeyId, String accessKeySecret, String regionId) throws Exception {
              Map<String, Object> cm = new HashMap<>();
              cm.put("regionId", regionId);
              cm.put("autoretry", "true");
              cm.put("accessKeyId", accessKeyId);
              cm.put("accessKeySecret", accessKeySecret);
              cm.put("connectTimeout", 15 * 1000);
              cm.put("readTimeout", 30 * 1000);
              cm.put("maxIdleConns", 200);
              cm.put("type", "access_key");
              cm.put("endpoint", "openplatform.aliyuncs.com");
              _runtime = RuntimeOptions.build(cm);
              com.aliyun.tearpc.models.Config authConfig = com.aliyun.tearpc.models.Config.build(cm);
              _authClient = new com.aliyun.openplatform20191219.Client(authConfig);
              //ossEndpointType = "internal";//aliyun-vpc
              _ossConfig = com.aliyun.oss.models.Config.build(TeaConverter.buildMap(
                      new TeaPair("accessKeySecret", accessKeySecret),
                      new TeaPair("type", "access_key"),
                      new TeaPair("protocol", _authClient._protocol),
                      new TeaPair("regionId", _authClient._regionId)
              ));
          }
      
          public String upload(InputStream inputStream) throws Exception {
              AuthorizeFileUploadRequest authRequest = AuthorizeFileUploadRequest.build(TeaConverter.buildMap(
                      new TeaPair("product", "imageseg"),
                      new TeaPair("regionId", _authClient._regionId)
              ));
              AuthorizeFileUploadResponse authResponse = _authClient.authorizeFileUploadWithOptions(authRequest, _runtime);
              com.aliyun.oss.models.Config ossConfig = new com.aliyun.oss.models.Config();
              com.aliyun.openapiutil.Client.convert(_ossConfig, ossConfig);
              ossConfig.accessKeyId = authResponse.accessKeyId;
              ossConfig.endpoint = com.aliyun.openapiutil.Client.getEndpoint(authResponse.endpoint, authResponse.useAccelerate, ossEndpointType);
              com.aliyun.oss.Client ossClient = new com.aliyun.oss.Client(ossConfig);
              FileField fileObj = FileField.build(TeaConverter.buildMap(
                      new TeaPair("filename", authResponse.objectKey),
                      new TeaPair("content", inputStream),
                      new TeaPair("contentType", "")
              ));
              PostObjectRequest.PostObjectRequestHeader ossHeader = PostObjectRequest.PostObjectRequestHeader.build(TeaConverter.buildMap(
                      new TeaPair("accessKeyId", authResponse.accessKeyId),
                      new TeaPair("policy", authResponse.encodedPolicy),
                      new TeaPair("signature", authResponse.signature),
                      new TeaPair("key", authResponse.objectKey),
                      new TeaPair("file", fileObj),
                      new TeaPair("successActionStatus", "201")
              ));
              PostObjectRequest uploadRequest = PostObjectRequest.build(TeaConverter.buildMap(
                      new TeaPair("bucketName", authResponse.bucket),
                      new TeaPair("header", ossHeader)
              ));
              com.aliyun.ossutil.models.RuntimeOptions ossRuntime = new com.aliyun.ossutil.models.RuntimeOptions();
              com.aliyun.openapiutil.Client.convert(_runtime, ossRuntime);
              ossClient.postObject(uploadRequest, ossRuntime);
              String imageURL = "http://" + authResponse.bucket + "." + authResponse.endpoint + "/" + authResponse.objectKey + "";
              return imageURL;
          }
      
          RuntimeOptions _runtime;
          com.aliyun.openplatform20191219.Client _authClient;
          com.aliyun.oss.models.Config _ossConfig;
          String ossEndpointType = null;
          static Map<String, ViapiFileUtilAdvance> _map = new ConcurrentHashMap<>();
      
      }
  • Python SDK
    请安装如下Python SDK 。
    pip install oss2
    pip install aliyun-python-sdk-viapiutils
    pip install aliyun-python-sdk-core
    pip install viapi-utils
    代码示例如下。
    from viapi.fileutils import FileUtils
    file_utils = FileUtils("your own accessKey","your own accessSecret")
    oss_url = file_utils.get_oss_url("http://xxx.jpeg","jpg",False)
    print(oss_url)
    oss_url = file_utils.get_oss_url("/home/xxx.mp4","mp4",True)
    print(oss_url)
  • Node.js SDK
    推荐使用NPM工具安装依赖包。
    npm install @alicloud/viapi-utils@^1.0.0 --save
    代码示例如下。
    // This file is auto-generated, don't edit it
    import ViapiUtil from '@alicloud/viapi-utils';
    
    
    export default class Client {
    
      static async main(): Promise<void> {
        // 您的AccessKeyID
        let accessKeyId: string = "accessKeyId";
        // 您的AccessKeySecret
        let accessKeySecret: string = "accessKeySecret";
        // 要上传的文件路径,url 或 filePath
        let fileUrl: string = "https://www.exampleFileUtl.com/file.jepg";
        // 上传成功后,返回上传后的文件地址
        let fileLoadAddress: string = await ViapiUtil.upload(accessKeyId, accessKeySecret, fileUrl);
      }
    
    }
  • PHP SDK
    推荐使用composer工具安装依赖包。
    composer require alibabacloud/viapi-utils
    代码示例如下。
    <?php
    
    // This file is auto-generated, don't edit it. Thanks.
    namespace Alibabacloud\SDK;
    
    use AlibabaCloud\SDK\ViapiUtils\ViapiUtils;
    
    class Client {
    
        /**
         * @return void
         * @throws \Exception
         */
        public static function main(){
            // 您的AccessKeyID
            $accessKeyId = "accessKeyId";
            // 您的AccessKeySecret
            $accessKeySecret = "accessKeySecret";
            // 要上传的文件路径,url 或 filePath
            $fileUrl = "https://www.exampleFileUtl.com/file.jepg";
            // 上传成功后,返回上传后的文件地址
            $fileLoadAddress = ViapiUtils::upload($accessKeyId, $accessKeySecret, $fileUrl);
        }
    }
  • GO SDK
    推荐使用GO工具安装依赖包。
    go get github.com/alibabacloud-go/viapi-utils/client:v1.0.0
    代码示例如下。
    // This file is auto-generated, don't edit it. Thanks.
    package main
    
    import (
      "fmt"
    
      "github.com/alibabacloud-go/tea/tea"
      viapiutil "github.com/alibabacloud-go/viapi-utils/client"
    )
    
    func main() {
      // 您的AccessKeyID
      accessKeyId := tea.String("accessKeyId")
      // 您的AccessKeySecret
      accessKeySecret := tea.String("accessKeySecret")
      // 要上传的文件路径,url 或 filePath
      fileUrl := tea.String("https://www.exampleFileUtl.com/file.jepg")
      // 上传成功后,返回上传后的文件地址
      fileLoadAddress, _err := viapiutil.Upload(accessKeyId, accessKeySecret, fileUrl)
      if _err != nil {
        fmt.Println(_err)
      }
      fmt.Println(fileLoadAddress)
    }
  • .NET SDK
    推荐使用Nuget工具安装依赖包。
    dotnet add package AlibabaCloud.SDK.VIAPIUtils
    代码示例如下。
    using System;
    //dotnet add package AlibabaCloud.SDK.VIAPIUtils
    using AlibabaCloud.SDK.VIAPI.Utils;
    
    namespace viapitest
    {
        class Program
        {
            static void Main(string[] args)
            {
                string accessKeyId="accessKeyId";   // 您的AccessKeyID
                string accessSecret="accessKeySecret";   // 您的AccessKeySecret
                string imageUrl="https://www.exampleFileUtl.com/file.jepg";  // 上传成功后,返回上传后的文件地址
                FileUtils fileobj=FileUtils.getInstance(accessKeyId,accessSecret);
                string result=fileobj.Upload(imageUrl);
                Console.WriteLine(result);
            }
        }
    }