curl \
-H "Authorization: Bearer [API Key]" \
-X GET https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov
const API_KEY = "Your API Key";
fetch("https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov", {
method: "GET",
headers: {
"Authorization": `Bearer ${API_KEY}`
}
})
.then((res) => res.json())
.then((json) => console.log(json))
.catch(console.error);
import requests
headers = {'Authorization': 'Bearer [API_KEY]'}
r = requests.get('https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov', headers=headers)
print(r.json())
<?php
require 'vendor/autoload.php'; // Composer auto-loader using Guzzle. See .../guzzlephp.org/en/stable/overview.html
$client = new GuzzleHttp\Client();
$res = $client->request(
'GET',
'https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov',
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer API_KEY'
]
]
);
echo json_encode(json_decode($res->getBody()), JSON_PRETTY_PRINT);
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
namespace MediaUploadUrlGETRequest_csharp
{
class MediaUploadUrl
{
static async Task Main(string[] args)
{
string API_KEY = "API_KEY";
string baseUrl = "https://api.ayrshare.com/api/media/uploadUrl";
// Build URL with query parameters
var uriBuilder = new UriBuilder(baseUrl);
var query = HttpUtility.ParseQueryString(string.Empty);
query["fileName"] = "test.mov";
query["contentType"] = "mov";
uriBuilder.Query = query.ToString();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + API_KEY);
try
{
HttpResponseMessage response = await client.GetAsync(uriBuilder.Uri);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
}
}
}
{
"accessUrl": "https://media.ayrshare.com/Aswmfs3dIEbwLSdhTlV2/test.mp4",
"contentType": "video/mp4",
"uploadUrl": "https://storage.googleapis.com/..."
}
{
"action": "upload",
"status": "error",
"code": 301,
"message": "The provided content-type 'movd' is not recognized."
}
Media
Завантаження великих медіафайлів
Для завантаження файлів розміром понад 10 МБ отримайте попередньо підписаний URL для завантаження файлу
GET
/
media
/
uploadUrl
curl \
-H "Authorization: Bearer [API Key]" \
-X GET https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov
const API_KEY = "Your API Key";
fetch("https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov", {
method: "GET",
headers: {
"Authorization": `Bearer ${API_KEY}`
}
})
.then((res) => res.json())
.then((json) => console.log(json))
.catch(console.error);
import requests
headers = {'Authorization': 'Bearer [API_KEY]'}
r = requests.get('https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov', headers=headers)
print(r.json())
<?php
require 'vendor/autoload.php'; // Composer auto-loader using Guzzle. See .../guzzlephp.org/en/stable/overview.html
$client = new GuzzleHttp\Client();
$res = $client->request(
'GET',
'https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov',
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer API_KEY'
]
]
);
echo json_encode(json_decode($res->getBody()), JSON_PRETTY_PRINT);
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
namespace MediaUploadUrlGETRequest_csharp
{
class MediaUploadUrl
{
static async Task Main(string[] args)
{
string API_KEY = "API_KEY";
string baseUrl = "https://api.ayrshare.com/api/media/uploadUrl";
// Build URL with query parameters
var uriBuilder = new UriBuilder(baseUrl);
var query = HttpUtility.ParseQueryString(string.Empty);
query["fileName"] = "test.mov";
query["contentType"] = "mov";
uriBuilder.Query = query.ToString();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + API_KEY);
try
{
HttpResponseMessage response = await client.GetAsync(uriBuilder.Uri);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
}
}
}
{
"accessUrl": "https://media.ayrshare.com/Aswmfs3dIEbwLSdhTlV2/test.mp4",
"contentType": "video/mp4",
"uploadUrl": "https://storage.googleapis.com/..."
}
{
"action": "upload",
"status": "error",
"code": 301,
"message": "The provided content-type 'movd' is not recognized."
}
Для завантаження файлів розміром понад 10 МБ отримайте попередньо підписаний URL для завантаження файлу.
Будь ласка, переконайтеся, що
- Максимальний розмір завантажуваного файлу — 5 ГБ.
- Попередньо підписаний URL для завантаження дійсний протягом 30 хвилин після створення.
- URL доступу доступний протягом 30 днів після завантаження. Усі опубліковані дописи не зазнають впливу у соціальних мережах. Заплановані дописи поза цим часовим інтервалом призведуть до помилок під час публікації.
Якщо ваші медіа вже доступні за зовнішнім URL, як-от у S3-бакеті, ви можете пропустити завантаження файлів до Ayrshare. Просто зробіть POST-запит до ендпоінту
/post з вашим зовнішньо доступним URL у параметрі тіла mediaURLs, і ваш файл буде автоматично завантажено.Параметри заголовка
Параметри запиту
string
Якщо contentType відсутній, потрібне повне ім’я файлу з розширенням.Ім’я файлу для завантаження. Має містити розширення, як-от .png, .jpg, .mov, .mp4 тощо.
string
Content-type медіа, що завантажується. Дійсні формати:
mp4, mov, png, jpg або jpeg.Наприклад, якщо файл — це файл Quicktime .mov, то contentType має бути mov.Якщо не вказано, буде використано application/octet-stream.curl \
-H "Authorization: Bearer [API Key]" \
-X GET https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov
const API_KEY = "Your API Key";
fetch("https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov", {
method: "GET",
headers: {
"Authorization": `Bearer ${API_KEY}`
}
})
.then((res) => res.json())
.then((json) => console.log(json))
.catch(console.error);
import requests
headers = {'Authorization': 'Bearer [API_KEY]'}
r = requests.get('https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov', headers=headers)
print(r.json())
<?php
require 'vendor/autoload.php'; // Composer auto-loader using Guzzle. See .../guzzlephp.org/en/stable/overview.html
$client = new GuzzleHttp\Client();
$res = $client->request(
'GET',
'https://api.ayrshare.com/api/media/uploadUrl?fileName=test.mov&contentType=mov',
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer API_KEY'
]
]
);
echo json_encode(json_decode($res->getBody()), JSON_PRETTY_PRINT);
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
namespace MediaUploadUrlGETRequest_csharp
{
class MediaUploadUrl
{
static async Task Main(string[] args)
{
string API_KEY = "API_KEY";
string baseUrl = "https://api.ayrshare.com/api/media/uploadUrl";
// Build URL with query parameters
var uriBuilder = new UriBuilder(baseUrl);
var query = HttpUtility.ParseQueryString(string.Empty);
query["fileName"] = "test.mov";
query["contentType"] = "mov";
uriBuilder.Query = query.ToString();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + API_KEY);
try
{
HttpResponseMessage response = await client.GetAsync(uriBuilder.Uri);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
}
}
}
Деталі відповіді
accessUrl— URL для доступу до медіафайлу після завантаження.contentType— content-type, встановлений для медіа, що завантажується. Використовуйте його в заголовку Content-Type під час завантаження медіа.uploadUrl— URL, який використовується для PUT медіафайлу. Див. нижче.
Додаткові приклади ендпоінтів
Процес завантаження великих файлів:- Отримайте
uploadURLтаaccessURLчерез ендпоінт/media/uploadUrl. Див. вище. - Завантажте файл через PUT з Content-Type, встановленим у повернутий
contentType. - Завантажте медіа за допомогою
--upload-fileз медіафайлом таuploadUrl. - При успішному завантаженні буде повернуто відповідь
200. - Після завантаження медіафайлу зробіть POST-запит до ендпоінту
/postзaccessUrlу параметрі тілаmediaUrls. - Попередньо підписаний URL для завантаження можна використати лише один раз. Якщо ви надіслали неправильний файл, ви маєте створити новий URL для завантаження. Відповідь про помилку не з’явиться, якщо файл не було успішно завантажено. Див. нижче про перевірку існування URL.
curl -X PUT \
-H 'Content-Type: video/mp4' \
--upload-file LOCAL_FILE_PATH uploadUrl
const fs = require("fs").promises;
const uploadFileToSignedUrl = async (signedUrl, filePath) => {
try {
const fileBuffer = await fs.readFile(filePath);
const response = await fetch(signedUrl, {
method: "PUT",
body: fileBuffer,
headers: {
"Content-Type": "video/mp4"
}
});
if (response.ok) {
console.log("File upload successful:", response.status);
} else {
console.error("File upload failed:", response.status);
}
} catch (error) {
console.error("Error uploading file:", error);
}
};
// Use the signed URL generated from the previous step
const signedUrl = "SIGNED_URL";
const filePath = "LOCAL_FILE_PATH";
uploadFileToSignedUrl(signedUrl, filePath);
import requests
def upload_file_to_signed_url(signed_url, file_path):
try:
with open(file_path, 'rb') as file:
response = requests.put(signed_url, data=file, headers={'Content-Type': 'video/mp4'})
if response.ok:
print("File upload successful:", response.status_code)
else:
print("File upload failed:", response.status_code)
except Exception as error:
print("Error uploading file:", error)
# Use the signed URL generated from the previous step
signed_url = "SIGNED_URL"
file_path = "LOCAL_FILE_PATH"
upload_file_to_signed_url(signed_url, file_path)
<?php
function uploadFileToSignedUrl($signedUrl, $filePath) {
try {
$fileHandle = fopen($filePath, 'rb');
if ($fileHandle === false) {
throw new Exception('Cannot open the file');
}
$ch = curl_init($signedUrl);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $fileHandle);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filePath));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: video/mp4'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
echo "File upload successful: " . $httpCode;
} else {
echo "File upload failed: " . $httpCode;
}
fclose($fileHandle);
curl_close($ch);
} catch (Exception $e) {
echo "Error uploading file: " . $e->getMessage();
}
}
// Use the signed URL generated from the previous step
$signedUrl = "SIGNED_URL";
$filePath = "LOCAL_FILE_PATH";
uploadFileToSignedUrl($signedUrl, $filePath);
?>
using System;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string signedUrl = "SIGNED_URL"; // Replace with your signed URL
string filePath = "LOCAL_FILE_PATH"; // Replace with your file path
try
{
await UploadFileToSignedUrl(signedUrl, filePath);
}
catch (Exception ex)
{
Console.WriteLine("Error uploading file: " + ex.Message);
}
}
static async Task UploadFileToSignedUrl(string signedUrl, string filePath)
{
using (var client = new HttpClient())
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (var content = new StreamContent(fileStream))
{
content.Headers.Add("Content-Type", "video/mp4");
var response = await client.PutAsync(signedUrl, content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("File upload successful: " + response.StatusCode);
}
else
{
Console.WriteLine("File upload failed: " + response.StatusCode);
}
}
}
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.nio.file.Path;
import java.io.IOException;
import java.nio.file.Files;
public class FileUploader {
public static void main(String[] args) {
String signedUrl = "SIGNED_URL"; // Replace with your signed URL
String filePath = "LOCAL_FILE_PATH"; // Replace with your file path
try {
uploadFileToSignedUrl(signedUrl, filePath);
} catch (IOException | InterruptedException e) {
System.out.println("Error uploading file: " + e.getMessage());
}
}
private static void uploadFileToSignedUrl(String signedUrl, String filePath) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(signedUrl))
.header("Content-Type", "image/jpg")
.PUT(BodyPublishers.ofFile(Path.of(filePath)))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
System.out.println("File upload successful: " + response.statusCode());
} else {
System.out.println("File upload failed: " + response.statusCode());
}
}
}
contentType, встановлений під час створення uploadUrl, відповідає Content-Type і типу файлу під час PUT-запиту файлу.
Наприклад, якщо ви встановили contentType як “image/png” під час створення uploadUrl, переконайтеся, що встановлено Content-Type: image/png, а завантажуваний файл закінчується на .png.
При успішному завантаженні буде повернуто відповідь 200.
Приклад завантаження двійкового файлу в Node.js
Ось приклад завантаження двійкового медіафайлу з використанням Node з JavaScript:const fs = require("fs");
const request = require("request");
const API_KEY = "Your API Key";
const fileName = "test.png";
const endpoint = `https://api.ayrshare.com/api/media/uploadUrl?fileName=${fileName}&contentType=png`;
const run = async () => {
request.get(
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`
},
url: endpoint
},
(err, res, body) => {
if (err) {
return console.error(err);
}
const json = JSON.parse(body);
console.log("Upload URL:", json);
return fs.createReadStream(`./${fileName}`).pipe(
request.put(
json.uploadUrl,
{
headers: {
"Content-Type": json.contentType
}
},
(err, httpsResponse, body) => {
if (err) {
console.error("err", err);
} else {
console.log(body);
}
}
)
);
}
);
};
run();
Приклад завантаження двійкового файлу в Postman
Ви також можете використовувати Postman для завантаження двійкового файлу доuploadUrl.
У Postman:
- Виберіть HTTP-метод
PUT. - Вставте ваш
uploadUrlу поле URL. Зверніть увагу, URL закінчиться через годину і може бути використаний лише один раз. Якщо ви робите виклик і він не вдається, ви маєте перегенеруватиuploadUrl. - У Headers встановіть
Content-Typeяк content type, повернутий з ендпоінту /uploadUrl. Наприклад:Content-Type: image/png. - Виберіть Body -> binary і виберіть файл для завантаження.
- Натисніть Send.
- Важливо: Не буде повернено жодної відповіді, тому ви маєте перевірити, чи було завантаження успішним, відкривши
accessUrl, повернутий з ендпоінту /uploadUrl, у браузері. Ви також можете використовувати ендпоінт перевірки URL.
Приклад JSON-файлу Postman
{
"accessUrl": "https://media.ayrshare.com/Aswmfs3dIEbwLSdhTlV2/test.mp4",
"contentType": "video/mp4",
"uploadUrl": "https://storage.googleapis.com/..."
}
{
"action": "upload",
"status": "error",
"code": 301,
"message": "The provided content-type 'movd' is not recognized."
}