### Java example: testUploadFile using FileUtils.upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk/blob/master/java/README.md This method demonstrates uploading a file (local path or URL) using FileUtils.getInstance with your access key and secret. It prints the resulting OSS URL. Replace 'xxx' with your actual credentials. ```java public static void testUploadFile() throws ClientException, IOException { String accessKey = "xxx"; String accessKeySecret = "xxx"; //String file = /home/admin/file/1.jpg 或者本地上传 String file = "https://fuss10.elemecdn.com/5/32/c17416d77817f2507d7fbdf15ef22jpeg.jpeg"; FileUtils fileUtils = FileUtils.getInstance(accessKey,accessKeySecret); String ossurl = fileUtils.upload(file); System.out.println(ossurl); } ``` -------------------------------- ### Install viapi-utils with go get Source: https://github.com/aliyun/alibabacloud-viapi-sdk/blob/master/golang/README.md Use this command to install the Alibaba Cloud Viapi SDK for Go when managing dependencies with go mod. Requires Go version newer than 1.12.0. ```sh $ go get github.com/alibabacloud-go/viapi-utils ``` -------------------------------- ### Basic usage example Source: https://github.com/aliyun/alibabacloud-viapi-sdk Shows how to instantiate FileUtils and call get_oss_url for both remote URL and local file inputs. Requires installing viapi-utils and dependencies. ```python from viapi.fileutils import FileUtils file_utils = FileUtils("your own accessKey", "your own accessSecret") # Remote URL input oss_url = file_utils.get_oss_url("http://xxx.jpeg", "jpg", False) print(oss_url) # Local file input oss_url = file_utils.get_oss_url("/home/xxx.mp4", "mp4", True) print(oss_url) ``` -------------------------------- ### Install via Composer Source: https://github.com/aliyun/alibabacloud-viapi-sdk/blob/master/php/README.md Use Composer to install the alibabacloud/viapi-utils package. ```bash composer require alibabacloud/viapi-utils ``` -------------------------------- ### Example: standalone usage Source: https://github.com/aliyun/alibabacloud-viapi-sdk Shows how to use subStringAfterLast, getNameFromUrl, and startsWith. The comment shows the expected output for the console.log call. ```typescript import Client from '@alicloud/viapi-tool'; const name = Client.subStringAfterLast(Client.getNameFromUrl('https://cdn.example.com/dir/a.jpg'), '/'); console.log(name); // a.jpg const isRemote = Client.startsWith('https://x', 'https://'); // true ``` -------------------------------- ### Install via Composer Source: https://github.com/aliyun/alibabacloud-viapi-sdk/blob/master/util/php/README-CN.md Use Composer to install the alibabacloud/viapi-tool package for PHP. ```bash composer require alibabacloud/viapi-tool ``` -------------------------------- ### Client.startsWith Source: https://github.com/aliyun/alibabacloud-viapi-sdk Checks if a string starts with a given prefix. Returns true if the origin string starts with the specified substring. ```APIDOC ## Client.startsWith ### Description Checks if a string starts with a given prefix. Returns true if the origin string starts with the specified substring. ### Method static startsWith(origin: string, sub: string): boolean ### Parameters - **origin** (string) - Required - The string to test - **sub** (string) - Required - The candidate prefix ### Response Returns boolean - true if origin starts with sub ``` -------------------------------- ### Install viapi Python SDK dependencies Source: https://github.com/aliyun/alibabacloud-viapi-sdk/blob/master/python/README.md Install the required Python packages for the viapi SDK: oss2, aliyun-python-sdk-viapiutils, aliyun-python-sdk-core, and viapi-utils. ```bash pip install oss2 pip install aliyun-python-sdk-viapiutils pip install aliyun-python-sdk-core pip install viapi-utils ``` -------------------------------- ### Use FileUtils to get OSS URL Source: https://github.com/aliyun/alibabacloud-viapi-sdk/blob/master/python/README.md Initialize FileUtils with your AccessKey and AccessSecret, then call get_oss_url to convert a file URL or local path to an OSS URL. The third parameter indicates whether the file is a video (True) or not (False). ```python 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) ``` -------------------------------- ### StartsWith Source: https://github.com/aliyun/alibabacloud-viapi-sdk Tests whether a string starts with a given prefix. Returns a Tea boolean value. ```APIDOC ## StartsWith ### Description Tests whether the origin string starts with the sub string. Returns a Tea boolean value. ### Method func StartsWith(origin *string, sub *string) (_result *bool) ### Parameters - **origin** (*string) - Required - The string to test - **sub** (*string) - Required - The candidate prefix ### Response Returns *bool (tea.Bool(strings.HasPrefix(...))) ``` -------------------------------- ### Example usage of viapi-tool client Source: https://github.com/aliyun/alibabacloud-viapi-sdk Shows how the upload SDK uses StartsWith, Decode, Match, SubStringAfterLast, GetNameFromUrl, GetStreamFromNet, and Close. Prints the file name or a network error for non-2xx responses. ```go package main import ( "fmt" viapitool "github.com/alibabacloud-go/viapi-tool/client" "github.com/alibabacloud-go/tea/tea" ) func main() { filePath := tea.String("https://example.com/a/b/photo.jpg") if tea.BoolValue(viapitool.StartsWith(filePath, tea.String("https://"))) { decoded := viapitool.Decode(filePath, tea.String("UTF-8")) name := viapitool.Match(decoded, tea.String("\\w+.(jpg|gif|png|jpeg|bmp|mov|mp4|avi)")) if tea.StringValue(name) == "" { name = viapitool.SubStringAfterLast(viapitool.GetNameFromUrl(decoded), tea.String("/")) } stream, err := viapitool.GetStreamFromNet(decoded) if err != nil { fmt.Println("network error:", err) // e.g. "Get ... failed, message: ..." for non-2xx return } defer viapitool.Close(stream) fmt.Println("file name:", tea.StringValue(name)) } } ``` -------------------------------- ### StartsWith Source: https://github.com/aliyun/alibabacloud-viapi-sdk Checks if a string starts with a specified substring. Returns false if the origin string is null or empty. ```APIDOC ## StartsWith ### Description Checks if a string starts with a specified substring. Returns false if the origin string is null or empty. ### Method StartsWith ### Signature `public static bool StartsWith(string origin, string sub)` ### Parameters - **origin** (string) - Required - The string to check. - **sub** (string) - Required - The substring to look for. ### Returns - **bool** - `false` if `origin` is null/empty, otherwise `origin.StartsWith(sub)`. ``` -------------------------------- ### startsWith method signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns true if origin starts with sub. Used by Client.upload to detect URL inputs (https:// or http://). ```typescript static startsWith(origin: string, sub: string): boolean ``` -------------------------------- ### Basic usage of client.Upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk Example of uploading a local file. Reads credentials from environment variables, wraps them with tea.String, and calls client.Upload. On error, panics; on success, prints the returned URL. ```go package main import ( "fmt" "os" "github.com/alibabacloud-go/viapi-utils/client" "github.com/alibabacloud-go/tea/tea" ) func main() { accessKeyId := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) accessKeySecret := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")) filePath := tea.String("/home/user/images/cat.jpg") ossUrl, err := client.Upload(accessKeyId, accessKeySecret, filePath) if err != nil { panic(err) } fmt.Println(tea.StringValue(ossUrl)) } ``` -------------------------------- ### C# FileUtils.getInstance and Upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk Singleton factory to get a FileUtils instance and upload methods to upload a file to OSS and return its public URL. ```APIDOC ## [C#] FileUtils.getInstance and Upload ### Description Singleton factory to get a FileUtils instance and upload methods to upload a file to OSS and return its public URL. ### Methods - `getInstance` - Returns a FileUtils instance. - `Upload(string)` - Uploads a file from a local path or URL. - `Upload(string, Stream)` - Uploads a file from a Stream. ### Details See [csharp-fileutils.md](api-reference/csharp-fileutils.md) for full details. ``` -------------------------------- ### StartsWith function signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Tests whether origin starts with sub. Returns *bool via tea.Bool(strings.HasPrefix(...)). ```go func StartsWith(origin *string, sub *string) (_result *bool) ``` -------------------------------- ### Optional indirect Maven dependencies for viapi-utils Source: https://github.com/aliyun/alibabacloud-viapi-sdk/blob/master/java/README.md These dependencies are indirect and should be added only if needed. They include aliyun-java-sdk-core, aliyun-sdk-oss, and commons-lang3 with specified versions. ```xml com.aliyun aliyun-java-sdk-core 4.4.8 com.aliyun.oss aliyun-sdk-oss 3.4.2 org.apache.commons commons-lang3 3.9 ``` -------------------------------- ### Java FileUtils.getInstance and upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk Singleton factory to get a FileUtils instance and upload methods to upload a file to OSS and return its public URL. ```APIDOC ## [Java] FileUtils.getInstance and upload ### Description Singleton factory to get a FileUtils instance and upload methods to upload a file to OSS and return its public URL. ### Methods - `getInstance` - Returns a FileUtils instance. - `upload(String)` - Uploads a file from a local path or URL. - `upload(String, InputStream)` - Uploads a file from an InputStream. ### Details See [java-fileutils.md](api-reference/java-fileutils.md) for full details. ``` -------------------------------- ### Example: stream lifecycle with error handling Source: https://github.com/aliyun/alibabacloud-viapi-sdk Demonstrates using getStreamFromNet and close. Note that stream 'error' events are not captured by getStreamFromNet's promise, so an error listener is attached. ```typescript import Client from '@alicloud/viapi-tool'; async function copyToOss(url: string) { const stream = await Client.getStreamFromNet(url); // resolves with the HTTP response stream try { // stream 'error' events are NOT captured by getStreamFromNet's promise stream.on('error', (err) => console.error('network error', err)); return stream; } catch (e) { Client.close(stream); throw e; } } ``` -------------------------------- ### Upload file using ViapiUtils Source: https://github.com/aliyun/alibabacloud-viapi-sdk/blob/master/php/README.md Example of uploading a file using ViapiUtils::upload with access key and secret. Catches TeaUnableRetryError to handle retry failures. ```php ", "", ""); var_dump($url); } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); } ``` -------------------------------- ### Basic usage of ViapiUtils::upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk Example from the README showing how to call the upload method with a local file path. Requires Composer autoload and valid credentials. ```php ", "", "/home/user/images/cat.jpg"); var_dump($url); ``` -------------------------------- ### Error handling example Source: https://github.com/aliyun/alibabacloud-viapi-sdk Demonstrates catching ClientException from STS token call failures and JSON/KeyError from unexpected STS responses. Requires importing json and ClientException. ```python import json from viapi.fileutils import FileUtils from aliyunsdkcore.acs_exception.exceptions import ClientException file_utils = FileUtils("", "") try: url = file_utils.get_oss_url("/tmp/receipt.png", "png", True) print(url) except ClientException as e: # Raised by do_action_with_exception when the STS token call fails print("STS error:", e.get_error_code(), e.get_error_msg()) except (json.JSONDecodeError, KeyError) as e: # Raised when the GetOssStsToken response has no Data payload print("Unexpected STS response:", e) ``` -------------------------------- ### Maven dependencies for viapi-utils and aliyun-java-sdk-viapiutils Source: https://github.com/aliyun/alibabacloud-viapi-sdk/blob/master/java/README.md Add these Maven dependencies to your project to use the viapi-utils library and the Alibaba Cloud SDK for viapiutils. The version numbers are 1.0.1 and 1.0.0 respectively. ```xml com.aliyun viapi-utils 1.0.1 com.aliyun aliyun-java-sdk-viapiutils 1.0.0 ``` -------------------------------- ### Remote URL input and error inspection Source: https://github.com/aliyun/alibabacloud-viapi-sdk Example of uploading a remote URL (https://example.com/videos/movie.mp4). Shows how to inspect a *tea.SDKError for the InvalidResponse code when the STS call fails, and prints the uploaded URL on success. ```go package main import ( "fmt" "github.com/alibabacloud-go/viapi-utils/client" "github.com/alibabacloud-go/tea/tea" ) func uploadRemote() { url1, err := client.Upload( tea.String(""), tea.String(""), tea.String("https://example.com/videos/movie.mp4"), ) if err != nil { // Match against the InvalidResponse SDKError when the STS call failed: if sd, ok := err.(*tea.SDKError); ok { fmt.Println("code:", sd.Code, "message:", sd.Message) } return } fmt.Println("uploaded:", tea.StringValue(url1)) } ``` -------------------------------- ### startsWith method signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Checks if a string contains a substring. Implemented with strpos, so it returns true when the substring occurs anywhere, not just at the start. ```php public static function startsWith($origin, $sub) ``` -------------------------------- ### startsWith Source: https://github.com/aliyun/alibabacloud-viapi-sdk Tests whether a substring occurs in a string. Note: implemented with strpos, so it returns true whenever the substring occurs anywhere in the origin string, not just at the start. ```APIDOC ## startsWith ### Description Tests whether a substring occurs in a string. Note: implemented with strpos, so it returns true whenever the substring occurs anywhere in the origin string, not just at the start. ### Method public static function startsWith($origin, $sub) ### Parameters - `$origin` (string) - Required - the string to test - `$sub` (string) - Required - the candidate prefix ### Returns `bool` — `false !== strpos($origin, $sub)` ``` -------------------------------- ### GetStreamFromNet Source: https://github.com/aliyun/alibabacloud-viapi-sdk Fetches a stream from a network URL via HTTP GET. Returns an error for non-2xx status codes. ```APIDOC ## GetStreamFromNet ### Description Performs http.Get(filepath). If resp.StatusCode is outside the range 200–300, reads the body and returns an error formatted as "Get %s failed, message: %s". Otherwise returns resp.Body. ### Method func GetStreamFromNet(filepath *string) (_result io.Reader, _err error) ### Parameters - **filepath** (*string) - Required - The URL to fetch ### Response Returns (io.Reader, error) — the response body on success, or an error for non-2xx status codes. ``` -------------------------------- ### File name extraction from URL example Source: https://github.com/aliyun/alibabacloud-viapi-sdk Shows how to extract a file name from a URL and create a stream for upload. Uses startsWith, match, subStringAfterLast, getNameFromUrl, getStreamFromNet, and close. Note that the anchor-wrapped match fails on full URLs, so it falls back to the last path segment. ```php ", ""); try (InputStream in = new FileInputStream("/tmp/receipt.png")) { String url = fileUtils.upload("receipt.png", in); // fileName is appended to the object key System.out.println(url); } } catch (ClientException | IOException e) { System.err.println("upload failed: " + e.getMessage()); } } } ``` -------------------------------- ### GetStreamFromNet function signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Performs http.Get(filepath). If resp.StatusCode is outside 200–300, reads the body and returns an error formatted as "Get %s failed, message: %s". Otherwise returns resp.Body. ```go func GetStreamFromNet(filepath *string) (_result io.Reader, _err error) ``` -------------------------------- ### Error handling with TeaUnableRetryError Source: https://github.com/aliyun/alibabacloud-viapi-sdk Example from the README demonstrating how to catch TeaUnableRetryError when uploading a URL. It prints the error message, info, last exception, and last request. ```php ", "", "https://example.com/pic.png"); var_dump($url); } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); } ``` -------------------------------- ### Python FileUtils.get_oss_url Source: https://github.com/aliyun/alibabacloud-viapi-sdk Instance method to get an OSS URL for a file. It uploads the file to OSS and returns the public URL. ```APIDOC ## [Python] FileUtils.get_oss_url ### Description Instance method to get an OSS URL for a file. It uploads the file to OSS and returns the public URL. ### Method get_oss_url ### Signature `get_oss_url(self, file_path, suffix, is_local)` ### Parameters - **file_path** - Required - Local file path or URL of the file to upload. - **suffix** - Required - File suffix/extension. - **is_local** - Required - Boolean indicating whether the file is local. ### Response #### Success Response - **string** - Public URL of the uploaded file. ``` -------------------------------- ### Go: client.Upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk Method to upload a file using Alibaba Cloud credentials. Requires access key ID, access key secret, and file path. ```APIDOC ## [METHOD] client.Upload ### Description Method to upload a file using Alibaba Cloud credentials. Requires access key ID, access key secret, and file path. ### Method Method ### Endpoint client.Upload ### Parameters - **accessKeyId** (*string) - Required - Alibaba Cloud access key ID - **accessKeySecret** (*string) - Required - Alibaba Cloud access key secret - **filePath** (*string) - Required - Path to the file to upload ### Response No response details provided. ``` -------------------------------- ### StartsWith method Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns bool — false if origin is null/empty, otherwise origin.StartsWith(sub). ```csharp public static bool StartsWith(string origin, string sub) ``` -------------------------------- ### C#: FileUtils.getInstance (static factory, singleton) Source: https://github.com/aliyun/alibabacloud-viapi-sdk Static factory method to obtain a singleton instance of FileUtils. Requires access key ID and access key secret. ```APIDOC ## [STATIC] FileUtils.getInstance ### Description Static factory method to obtain a singleton instance of FileUtils. Requires access key ID and access key secret. ### Method Static ### Endpoint FileUtils.getInstance ### Parameters - **accessKeyId** (string) - Required - Alibaba Cloud access key ID - **accessKeySecret** (string) - Required - Alibaba Cloud access key secret ### Response No response details provided. ``` -------------------------------- ### Java: FileUtils.getInstance (static factory, singleton) Source: https://github.com/aliyun/alibabacloud-viapi-sdk Static factory method to obtain a singleton instance of FileUtils. Requires access key ID and access key secret. ```APIDOC ## [STATIC] FileUtils.getInstance ### Description Static factory method to obtain a singleton instance of FileUtils. Requires access key ID and access key secret. ### Method Static ### Endpoint FileUtils.getInstance ### Parameters - **accessKeyId** (String) - Required - Alibaba Cloud access key ID - **accessKeySecret** (String) - Required - Alibaba Cloud access key secret ### Response No response details provided. ``` -------------------------------- ### Python: FileUtils(access_key, access_secret) (constructor) Source: https://github.com/aliyun/alibabacloud-viapi-sdk Constructor to create a FileUtils instance. Requires access key and access secret. ```APIDOC ## [CONSTRUCTOR] FileUtils(access_key, access_secret) ### Description Constructor to create a FileUtils instance. Requires access key and access secret. ### Method Constructor ### Endpoint FileUtils(access_key, access_secret) ### Parameters - **access_key** (str) - Required - Alibaba Cloud access key - **access_secret** (str) - Required - Alibaba Cloud access secret ### Response No response details provided. ``` -------------------------------- ### FileUtils.__init__ Source: https://github.com/aliyun/alibabacloud-viapi-sdk Constructor for the FileUtils class. Initializes an AcsClient for the cn-shanghai region with the provided Alibaba Cloud credentials. ```APIDOC ## FileUtils.__init__ ### Description Constructor for the FileUtils class. Initializes an AcsClient for the cn-shanghai region with the provided Alibaba Cloud credentials. ### Method Constructor ### Signature ```python def __init__(self, access_key, access_secret): ``` ### Parameters - `access_key` (str) - Required - Alibaba Cloud access key ID; stored as `self.access_key` and used as the first OSS object-name path segment - `access_secret` (str) - Required - Alibaba Cloud access key secret ### Behavior Creates `self.client = AcsClient(access_key, access_secret, "cn-shanghai")` — the region is hardcoded. ``` -------------------------------- ### Match method Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns string — Regex.Match(origin, regrex).Value on success, else string.Empty. ```csharp public static string Match(string origin, string regrex) ``` -------------------------------- ### TypeScript: Client.upload (static) Source: https://github.com/aliyun/alibabacloud-viapi-sdk Static method to upload a file using Alibaba Cloud credentials. Requires access key ID, access key secret, and file path. ```APIDOC ## [STATIC] Client.upload ### Description Static method to upload a file using Alibaba Cloud credentials. Requires access key ID, access key secret, and file path. ### Method Static ### Endpoint Client.upload ### Parameters - **accessKeyId** (string) - Required - Alibaba Cloud access key ID - **accessKeySecret** (string) - Required - Alibaba Cloud access key secret - **filePath** (string) - Required - Path to the file to upload ### Response No response details provided. ``` -------------------------------- ### Basic usage of FileUtils.Upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk Shows how to instantiate FileUtils and upload a local file or a remote URL. The remote URL's file name is parsed from the URL. ```csharp using AlibabaCloud.SDK.VIAPI.Utils; class Program { static void Main() { string accessKeyId = ""; string accessKeySecret = ""; FileUtils fileUtils = FileUtils.getInstance(accessKeyId, accessKeySecret); // local file string url1 = fileUtils.Upload(@"C:\images\cat.jpg"); System.Console.WriteLine(url1); // remote URL — the file name is parsed from the URL string url2 = fileUtils.Upload("https://example.com/pictures/photo.png"); System.Console.WriteLine(url2); } } ``` -------------------------------- ### PHP: ViapiUtils::upload (static) Source: https://github.com/aliyun/alibabacloud-viapi-sdk Static method to upload a file using Alibaba Cloud credentials. Requires access key ID, access key secret, and file path. ```APIDOC ## [STATIC] ViapiUtils::upload ### Description Static method to upload a file using Alibaba Cloud credentials. Requires access key ID, access key secret, and file path. ### Method Static ### Endpoint ViapiUtils::upload ### Parameters - **$accessKeyId** (string) - Required - Alibaba Cloud access key ID - **$accessKeySecret** (string) - Required - Alibaba Cloud access key secret - **$filePath** (string) - Required - Path to the file to upload ### Response No response details provided. ``` -------------------------------- ### Catch GetStreamFromNet error in Go Source: https://github.com/aliyun/alibabacloud-viapi-sdk Consumer code that calls viapitool.GetStreamFromNet and logs the error. The error message includes the URL and the HTTP status, e.g. 'Get http://example.com/img.jpg failed, message: 404 Not Found'. ```go stream, err := viapitool.GetStreamFromNet(tea.String("http://example.com/img.jpg")) if err != nil { // e.g. "Get http://example.com/img.jpg failed, message: 404 Not Found" log.Println(err) } ``` -------------------------------- ### Match Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns the first regex submatch found in the origin string. Returns an empty string when nothing matches. ```APIDOC ## Match ### Description Returns the first regex submatch via regexp.MustCompile(...).FindStringSubmatch, or "" when nothing matches. ### Method func Match(origin *string, regrex *string) (_result *string) ### Parameters - **origin** (*string) - Required - The string to search - **regrex** (*string) - Required - The regular expression pattern ### Response Returns *string — the first regex submatch, or "" when nothing matches. ``` -------------------------------- ### Basic usage of Client.Close Source: https://github.com/aliyun/alibabacloud-viapi-sdk Shows basic usage of Client.Close(Stream) to close a stream obtained from Client.GetStreamFromNet. The example also uses Client.SubStringAfterLast and Client.GetNameFromUrl to extract a filename from a URL. The using statement is an alternative to calling Close. ```csharp using System; using System.IO; using AlibabaCloud.ViapiTool; class Program { static void Main() { string name = Client.SubStringAfterLast( Client.GetNameFromUrl("https://cdn.example.com/dir/a.jpg"), "/"); Console.WriteLine(name); // a.jpg using (Stream s = Client.GetStreamFromNet("https://example.com/file.png")) { // upload s ... } // or Client.Close(s); } } ``` -------------------------------- ### Client.getStreamFromPath Source: https://github.com/aliyun/alibabacloud-viapi-sdk Creates a readable stream from a filesystem path. Resolves with the stream; errors surface as stream 'error' events. ```APIDOC ## Client.getStreamFromPath ### Description Creates a readable stream from a filesystem path. Resolves with the stream; errors surface as stream 'error' events. ### Method static async getStreamFromPath(filepath: string): Promise ### Parameters - **filepath** (string) - Required - The filesystem path ### Response Returns Promise - A fs.createReadStream(filepath) stream. Resolves with the stream; errors from createReadStream surface as stream 'error' events, not as promise rejections ``` -------------------------------- ### Basic usage of Client.upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk Imports the default `Client` class and calls `upload` with access key ID, secret, and a local file path. Logs the returned OSS URL. The URL format is `http://viapi-customer-temp.oss-cn-shanghai.aliyuncs.com//cat.jpg`. ```typescript import Client from '@alicloud/viapi-utils'; async function main() { const ossUrl = await Client.upload('', '', '/home/user/images/cat.jpg'); console.log(ossUrl); // http://viapi-customer-temp.oss-cn-shanghai.aliyuncs.com//cat.jpg } main().catch(console.error); ``` -------------------------------- ### Go client.Upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk Function to upload a file to OSS and return its public URL. It acquires STS credentials, uploads the file, and returns the URL. ```APIDOC ## [Go] client.Upload ### Description Function to upload a file to OSS and return its public URL. It acquires STS credentials, uploads the file, and returns the URL. ### Method func Upload ### Signature `func Upload(accessKeyId *string, accessKeySecret *string, filePath *string) (_result *string, _err error)` ### Parameters - **accessKeyId** (*string) - Required - Alibaba Cloud AccessKey ID. - **accessKeySecret** (*string) - Required - Alibaba Cloud AccessKey Secret. - **filePath** (*string) - Required - Local file path or HTTP/HTTPS URL of the file to upload. ### Response #### Success Response - **_result** (*string) - Public URL of the uploaded file. - **_err** (error) - Error, if any. ``` -------------------------------- ### GetNameFromUrl function signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns the URL path (u.Path), or "" when url.Parse fails. ```go func GetNameFromUrl(urlStr *string) (_result *string) ``` -------------------------------- ### Match Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns the first match of a regular expression in a string. Returns an empty string if no match is found. ```APIDOC ## Match ### Description Returns the first match of a regular expression in a string. Returns an empty string if no match is found. ### Method Match ### Signature `public static string Match(string origin, string regrex)` ### Parameters - **origin** (string) - Required - The string to search. - **regrex** (string) - Required - The regular expression pattern. ### Returns - **string** - `Regex.Match(origin, regrex).Value` on success, else `string.Empty`. ``` -------------------------------- ### GetStreamFromPath Source: https://github.com/aliyun/alibabacloud-viapi-sdk Opens a file from the local filesystem and returns its stream. Returns an error if the file cannot be opened. ```APIDOC ## GetStreamFromPath ### Description Performs os.Open(filepath) and returns the file stream. ### Method func GetStreamFromPath(filepath *string) (_result io.Reader, _err error) ### Parameters - **filepath** (*string) - Required - The filesystem path to open ### Response Returns (io.Reader, error) — the file stream on success, or an error. ``` -------------------------------- ### C#: FileUtils.Upload(string filePath) Source: https://github.com/aliyun/alibabacloud-viapi-sdk Instance method to upload a file by file path. Requires the file path. ```APIDOC ## [METHOD] FileUtils.Upload(string filePath) ### Description Instance method to upload a file by file path. Requires the file path. ### Method Method ### Endpoint FileUtils.Upload(string filePath) ### Parameters - **filePath** (string) - Required - Path to the file to upload ### Response No response details provided. ``` -------------------------------- ### Exported function signatures of viapi-tool client Source: https://github.com/aliyun/alibabacloud-viapi-sdk Lists the nine top-level functions exported by the client package. All string parameters and returns are Tea *string values; use tea.String(...) / tea.StringValue(...). ```go func StartsWith(origin *string, sub *string) (_result *bool) func Match(origin *string, regrex *string) (_result *string) func Decode(origin *string, decodeType *string) (_result *string) func GetNameFromUrl(urlStr *string) (_result *string) func GetNameFromPath(pathStr *string) (_result *string) func SubStringAfterLast(path *string, sub *string) (_result *string) func GetStreamFromNet(filepath *string) (_result io.Reader, _err error) func GetStreamFromPath(filepath *string) (_result io.Reader, _err error) func Close(body io.Reader) ``` -------------------------------- ### C#: FileUtils.Upload(string fileName, Stream stream) Source: https://github.com/aliyun/alibabacloud-viapi-sdk Instance method to upload a file from a stream. Requires file name and stream. ```APIDOC ## [METHOD] FileUtils.Upload(string fileName, Stream stream) ### Description Instance method to upload a file from a stream. Requires file name and stream. ### Method Method ### Endpoint FileUtils.Upload(string fileName, Stream stream) ### Parameters - **fileName** (string) - Required - Name of the file - **stream** (Stream) - Required - Stream of the file ### Response No response details provided. ``` -------------------------------- ### FileUtils class definition Source: https://github.com/aliyun/alibabacloud-viapi-sdk Singleton-style facade with private constructor, cached per access key pair, and a regex for supported file extensions. ```csharp public class FileUtils { AlibabaCloud.SDK.Viapiutils20200401.Client client; string endpoint = "viapiutils.cn-shanghai.aliyuncs.com"; string accessKeyId; Regex fileNameRegex = new Regex("\\w+.(jpg|gif|png|jpeg|bmp|mov|mp4|avi)"); static Dictionary map = new Dictionary(); private static object syncObj = new object(); } ``` -------------------------------- ### FileUtils.__init__ signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Constructor signature for FileUtils. Takes access key and secret, stores them, and creates an AcsClient for the hardcoded cn-shanghai region. ```python def __init__(self, access_key, access_secret): ``` -------------------------------- ### Decode method Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns string — HttpUtility.UrlDecode(origin, Encoding.GetEncoding(decodeType)). Throws ArgumentException for unknown encoding names. ```csharp public static string Decode(string origin, string decodeType) ``` -------------------------------- ### Java: FileUtils.upload(String fileName, InputStream stream) Source: https://github.com/aliyun/alibabacloud-viapi-sdk Instance method to upload a file from an input stream. Requires file name and stream. ```APIDOC ## [METHOD] FileUtils.upload(String fileName, InputStream stream) ### Description Instance method to upload a file from an input stream. Requires file name and stream. ### Method Method ### Endpoint FileUtils.upload(String fileName, InputStream stream) ### Parameters - **fileName** (String) - Required - Name of the file - **stream** (InputStream) - Required - Input stream of the file ### Response No response details provided. ``` -------------------------------- ### Java: FileUtils.upload(String filePath) Source: https://github.com/aliyun/alibabacloud-viapi-sdk Instance method to upload a file by file path. Requires the file path. ```APIDOC ## [METHOD] FileUtils.upload(String filePath) ### Description Instance method to upload a file by file path. Requires the file path. ### Method Method ### Endpoint FileUtils.upload(String filePath) ### Parameters - **filePath** (String) - Required - Path to the file to upload ### Response No response details provided. ``` -------------------------------- ### Upload Source: https://github.com/aliyun/alibabacloud-viapi-sdk Uploads a local file or remote URL to Alibaba Cloud OSS and returns the public object URL. It obtains temporary STS credentials via the Viapiutils service, then uploads the file to the viapi-customer-temp bucket. ```APIDOC ## Upload ### Description Uploads a local file or remote URL to Alibaba Cloud OSS and returns the public object URL. It obtains temporary STS credentials via the Viapiutils service, then uploads the file to the viapi-customer-temp bucket. ### Function Signature ```go func Upload(accessKeyId *string, accessKeySecret *string, filePath *string) (_result *string, _err error) ``` ### Parameters - **accessKeyId** (*string) - Required - Alibaba Cloud access key ID; a Tea `*string` (wrap with `tea.String(...)`) - **accessKeySecret** (*string) - Required - Alibaba Cloud access key secret - **filePath** (*string) - Required - local path or `http://` / `https://` URL of the file to upload ### Return Value - **result** (*string) - On success, a Tea `*string` holding the public object URL `http://viapi-customer-temp.oss-cn-shanghai.aliyuncs.com/{objectName}` - **err** (error) - On failure, non-nil error; `result` is nil ### Errors - **InvalidResponse** (*tea.SDKError) - Returned when `GetOssStsToken` returns a response whose `Data` is unset - Errors from `viapiutils20200401.NewClient`, `GetOssStsToken`, `viapitool.GetStreamFromNet`/`GetStreamFromPath`, `oss.NewClient`, `PutObject` are propagated unchanged ### Request Example ```go package main import ( "fmt" "os" "github.com/alibabacloud-go/viapi-utils/client" "github.com/alibabacloud-go/tea/tea" ) func main() { accessKeyId := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) accessKeySecret := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")) filePath := tea.String("/home/user/images/cat.jpg") ossUrl, err := client.Upload(accessKeyId, accessKeySecret, filePath) if err != nil { panic(err) } fmt.Println(tea.StringValue(ossUrl)) } ``` ### Request Example (Remote URL) ```go package main import ( "fmt" "github.com/alibabacloud-go/viapi-utils/client" "github.com/alibabacloud-go/tea/tea" ) func uploadRemote() { url1, err := client.Upload( tea.String(""), tea.String(""), tea.String("https://example.com/videos/movie.mp4"), ) if err != nil { // Match against the InvalidResponse SDKError when the STS call failed: if sd, ok := err.(*tea.SDKError); ok { fmt.Println("code:", sd.Code, "message:", sd.Message) } return } fmt.Println("uploaded:", tea.StringValue(url1)) } ``` ``` -------------------------------- ### FileUtils.getInstance Source: https://github.com/aliyun/alibabacloud-viapi-sdk Static factory method that returns a cached FileUtils instance for the given access key pair. The instance is created on first call and cached in a thread-safe manner. ```APIDOC ## FileUtils.getInstance ### Description Static factory method that returns a cached FileUtils instance for the given access key pair. The instance is created on first call and cached in a thread-safe manner. ### Method Static factory ### Signature ```csharp public static FileUtils getInstance(string accessKeyId, string accessKeySecret) ``` ### Parameters - **accessKeyId** (string) - Required - Alibaba Cloud access key ID; first OSS object-name path segment - **accessKeySecret** (string) - Required - Alibaba Cloud access key secret ### Return - **FileUtils** - The cached instance for key `accessKeyId + accessKeySecret`, created on first call. ``` -------------------------------- ### Decode Source: https://github.com/aliyun/alibabacloud-viapi-sdk URL-decodes a string using the specified encoding. Throws ArgumentException for unknown encoding names. ```APIDOC ## Decode ### Description URL-decodes a string using the specified encoding. Throws ArgumentException for unknown encoding names. ### Method Decode ### Signature `public static string Decode(string origin, string decodeType)` ### Parameters - **origin** (string) - Required - The encoded string. - **decodeType** (string) - Required - An encoding name resolved by `System.Text.Encoding.GetEncoding(decodeType)` (e.g. `"UTF-8"`). ### Returns - **string** - `HttpUtility.UrlDecode(origin, Encoding.GetEncoding(decodeType))`. ``` -------------------------------- ### GetStreamFromPath function signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns (io.Reader, error) — os.Open(filepath). ```go func GetStreamFromPath(filepath *string) (_result io.Reader, _err error) ``` -------------------------------- ### GetNameFromPath function signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns the file base name via os.Stat, or "" when the stat fails. ```go func GetNameFromPath(pathStr *string) (_result *string) ``` -------------------------------- ### Client class definition Source: https://github.com/aliyun/alibabacloud-viapi-sdk The Client class exposes static utility methods for URL/path parsing, string manipulation, and stream handling. Readable is imported from Node.js stream. ```typescript export default class Client { static startsWith(origin: string, sub: string): boolean static match(origin: string, regrex: string): string static decode(origin: string, decodeType: string): string static getNameFromUrl(urlStr: string): string static getNameFromPath(pathStr: string): string static subStringAfterLast(path: string, sub: string): string static async getStreamFromNet(url: string): Promise static async getStreamFromPath(filepath: string): Promise static close(body: Readable): void } ``` -------------------------------- ### GetNameFromPath Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns the file base name from a filesystem path. Returns an empty string when the stat fails. ```APIDOC ## GetNameFromPath ### Description Returns the file base name via os.Stat, or "" when the stat fails. ### Method func GetNameFromPath(pathStr *string) (_result *string) ### Parameters - **pathStr** (*string) - Required - The filesystem path ### Response Returns *string — the file base name, or "" on stat failure. ``` -------------------------------- ### Match function signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns the first regex submatch via regexp.MustCompile(...).FindStringSubmatch, or "" when nothing matches. ```go func Match(origin *string, regrex *string) (_result *string) ``` -------------------------------- ### SubStringAfterLast method Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns string — if sub is null/empty, the whole path; otherwise the substring after the last sub (path.LastIndexOf(sub)); string.Empty when sub is not present. ```csharp public static string SubStringAfterLast(string path, string sub) ``` -------------------------------- ### GetStreamFromPath method Source: https://github.com/aliyun/alibabacloud-viapi-sdk Returns Stream — File.OpenRead(filepath); throws FileNotFoundException/IOException for missing or unreadable files. ```csharp public static Stream GetStreamFromPath(string filepath) ``` -------------------------------- ### FileUtils.Upload signature Source: https://github.com/aliyun/alibabacloud-viapi-sdk Uploads a local file path or http/https URL and returns the public OSS URL. URL inputs are URL-decoded and matched against fileNameRegex, falling back to the last path segment. ```csharp public string Upload(string filePath) ```