Skip to content

Commit

Permalink
update netcore/object-storage
Browse files Browse the repository at this point in the history
  • Loading branch information
A-Najmabadi committed Jan 10, 2024
1 parent e4885a0 commit c1253a5
Showing 1 changed file with 166 additions and 97 deletions.
263 changes: 166 additions & 97 deletions pages/app-deploy/netcore/object-storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ LIARA_SECRET_KEY=<Secret Key>`}
می‌کنید؛ می‌توانید با استفاده از دستور زیر، پکیج DotEnv را نصب کنید.
</p>

<Highlight className="shell">{`dotnet add package dotenv.net`}</Highlight>
<Highlight className="shell">{`dotnet add package DotNetEnv`}</Highlight>

<h3 id="how-to-use">نحوه‌ی استفاده</h3>
<p>
Expand All @@ -112,12 +112,19 @@ LIARA_SECRET_KEY=<Secret Key>`}
آیتم‌های موجود در یک باکت
</li>
<li>
اجرای دستور <span className="code">dotnet run download</span> برای
دانلود یک فایل مشخص از باکت و ذخیره آن
اجرای دستور{" "}
<span className="code">dotnet run download &lt;object-name&gt;</span>{" "}
برای دانلود یک فایل مشخص از باکت و ذخیره آن
</li>
<li>
اجرای دستور <span className="code">dotnet run upload</span> برای آپلود
یک فایل مشخص درون باکت
اجرای دستور{" "}
<span className="code">dotnet run delete &lt;object-name&gt;</span> برای
حدف یک فایل مشخص از باکت
</li>
<li>
اجرای دستور{" "}
<span className="code">dotnet run upload &lt;object-name&gt;</span> برای
آپلود یک فایل مشخص درون باکت
</li>
<li>
اجرای دستور <span className="code">dotnet run geturls</span> برای دریافت
Expand All @@ -131,28 +138,33 @@ LIARA_SECRET_KEY=<Secret Key>`}

<Highlight className="csharp">
{`using System;
using System.Collections.Generic;
using Amazon;
using System.IO;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;
using DotNetEnv;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// loading env variables
// Load environment variables
Env.Load();
// setting env variables
// Set environment variables
string accessKey = Env.GetString("LIARA_ACCESS_KEY");
string secretKey = Env.GetString("LIARA_SECRET_KEY");
string bucketName = Env.GetString("LIARA_BUCKET_NAME");
string endpoint = Env.GetString("LIARA_ENDPOINT");
// making s3 connections
// Check for the existence of required variables
if (string.IsNullOrEmpty(accessKey) || string.IsNullOrEmpty(secretKey) || string.IsNullOrEmpty(bucketName) || string.IsNullOrEmpty(endpoint))
{
Console.WriteLine("Error: Missing required environment variables.");
return;
}
// Create S3 client
var config = new AmazonS3Config
{
ServiceURL = endpoint,
Expand All @@ -162,113 +174,170 @@ class Program
var credentials = new Amazon.Runtime.BasicAWSCredentials(accessKey, secretKey);
using var client = new AmazonS3Client(credentials, config);
if (args.Length > 0)
// Check for command
if (args.Length == 0)
{
string command = args[0];
Console.WriteLine("Please provide a command. Available commands: list, download, upload, geturls, getpermanenturls, listbuckets, delete");
return;
}
if (command == "list")
{
// listing items from bucket
ListObjectsV2Request request = new ListObjectsV2Request
{
BucketName = bucketName
};
ListObjectsV2Response response = client.ListObjectsV2Async(request).Result;
string command = args[0];
foreach (S3Object entry in response.S3Objects)
switch (command)
{
case "list":
await ListObjectsAsync(client, bucketName);
break;
case "download":
if (args.Length < 2)
{
Console.WriteLine($"File: {entry.Key} (Size: {entry.Size} bytes)");
Console.WriteLine("Please provide the object key to download.");
return;
}
}
else if (command == "download")
{
string objectKey = "wordpress.png";
string filePath = "downloaded_file.png";
try
await DownloadObjectAsync(client, bucketName, args[1], Path.Combine(Directory.GetCurrentDirectory(), args[1]));
break;
case "upload":
if (args.Length < 2)
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = objectKey
};
using GetObjectResponse response = await client.GetObjectAsync(request);
using Stream responseStream = response.ResponseStream;
using FileStream fileStream = File.Create(filePath);
await responseStream.CopyToAsync(fileStream);
Console.WriteLine($"File '{objectKey}' downloaded successfully.");
Console.WriteLine("Please provide the object key for upload.");
return;
}
catch (AmazonS3Exception e)
await UploadObjectAsync(client, bucketName, Path.Combine(Directory.GetCurrentDirectory(), args[1]), args[1]);
break;
case "geturls":
await GetUrlsAsync(client, bucketName, 1);
break;
case "getpermanenturls":
await GetUrlsAsync(client, bucketName, 10);
break;
case "listbuckets":
await ListBucketsAsync(client);
break;
case "delete":
if (args.Length < 2)
{
Console.WriteLine($"Error: {e.Message}");
Console.WriteLine("Please provide the object key to delete.");
return;
}
}
else if (command == "upload")
{
string filePath = "downloaded_file.png"; // مسیر فایل محلی
string objectKey = "uploaded.png"; // نام فایل در سبد
await DeleteObjectAsync(client, bucketName, args[1]);
break;
default:
Console.WriteLine("Invalid command. Available commands: list, download, upload, geturls, getpermanenturls, listbuckets, delete");
break;
}
}
static async Task ListObjectsAsync(IAmazonS3 client, string bucketName)
{
ListObjectsV2Request request = new ListObjectsV2Request
{
BucketName = bucketName
};
ListObjectsV2Response response = await client.ListObjectsV2Async(request);
try
{
using FileStream fileStream = new FileStream(filePath, FileMode.Open);
foreach (S3Object entry in response.S3Objects)
{
Console.WriteLine($"File: {entry.Key} (Size: {entry.Size} bytes)");
}
}
PutObjectRequest request = new PutObjectRequest
{
BucketName = bucketName,
Key = objectKey,
InputStream = fileStream
};
static async Task DownloadObjectAsync(IAmazonS3 client, string bucketName, string objectKey, string filePath)
{
try
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = objectKey
};
await client.PutObjectAsync(request);
using GetObjectResponse response = await client.GetObjectAsync(request);
using Stream responseStream = response.ResponseStream;
using FileStream fileStream = File.Create(filePath);
await responseStream.CopyToAsync(fileStream);
Console.WriteLine($"File '{objectKey}' downloaded successfully.");
}
catch (AmazonS3Exception e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
Console.WriteLine($"File '{objectKey}' uploaded successfully.");
}
catch (AmazonS3Exception e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
else if (command == "geturls")
static async Task UploadObjectAsync(IAmazonS3 client, string bucketName, string filePath, string objectKey)
{
try
{
using FileStream fileStream = new FileStream(filePath, FileMode.Open);
PutObjectRequest request = new PutObjectRequest
{
ListObjectsV2Request request = new ListObjectsV2Request
{
BucketName = bucketName
};
ListObjectsV2Response response = client.ListObjectsV2Async(request).Result;
BucketName = bucketName,
Key = objectKey,
InputStream = fileStream
};
foreach (S3Object entry in response.S3Objects)
{
GetPreSignedUrlRequest urlRequest = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Key = entry.Key,
Expires = DateTime.Now.AddHours(1) // زمان انقضا (یک ساعت)
};
string url = client.GetPreSignedURL(urlRequest);
Console.WriteLine($"File: {entry.Key}, URL: {url}");
}
}
else if (command == "listbuckets")
await client.PutObjectAsync(request);
Console.WriteLine($"File '{objectKey}' uploaded successfully.");
}
catch (AmazonS3Exception e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
static async Task GetUrlsAsync(IAmazonS3 client, string bucketName, int expiresInHours)
{
ListObjectsV2Request request = new ListObjectsV2Request
{
BucketName = bucketName
};
ListObjectsV2Response response = await client.ListObjectsV2Async(request);
foreach (S3Object entry in response.S3Objects)
{
GetPreSignedUrlRequest urlRequest = new GetPreSignedUrlRequest
{
ListBucketsResponse response = client.ListBucketsAsync().Result;
BucketName = bucketName,
Key = entry.Key,
Expires = DateTime.Now.AddHours(expiresInHours)
};
string url = client.GetPreSignedURL(urlRequest);
Console.WriteLine($"File: {entry.Key}, URL: {url}");
}
}
Console.WriteLine("Available Buckets:");
foreach (S3Bucket bucket in response.Buckets)
{
Console.WriteLine(bucket.BucketName);
}
}
else
static async Task ListBucketsAsync(IAmazonS3 client)
{
ListBucketsResponse response = await client.ListBucketsAsync();
Console.WriteLine("Available Buckets:");
foreach (S3Bucket bucket in response.Buckets)
{
Console.WriteLine(bucket.BucketName);
}
}
static async Task DeleteObjectAsync(IAmazonS3 client, string bucketName, string objectKey)
{
try
{
DeleteObjectRequest deleteRequest = new DeleteObjectRequest
{
Console.WriteLine("Invalid command. Available commands: list, download, upload, geturls, getpermanenturls, listbuckets");
}
BucketName = bucketName,
Key = objectKey
};
await client.DeleteObjectAsync(deleteRequest);
Console.WriteLine($"File '{objectKey}' deleted successfully.");
}
else
catch (AmazonS3Exception e)
{
Console.WriteLine("Please provide a command. Available commands: list, download, upload, geturls, getpermanenturls, listbuckets");
Console.WriteLine($"Error: {e.Message}");
}
}
}`}
}
`}
</Highlight>

<h3 id="how-to-use-in-controller">نحوه‌ی استفاده در کنترلر</h3>
Expand Down

0 comments on commit c1253a5

Please sign in to comment.