Advertisement
keselyoleren

Untitled

Jun 26th, 2023
796
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.54 KB | None | 0 0
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Net.Http.Headers;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10.  
  11. class Program
  12. {
  13.     static async Task Main(string[] args)
  14.     {
  15.         Console.WriteLine("Enter the full path of file you want to upload:");
  16.         string filePath = Console.ReadLine();
  17.  
  18.         // await Login("jionglelam@phaostech.com", "Admin!234");
  19.         await Login("indarto@neurabot.ai", "Admin!234!");
  20.         await UploadFile(filePath);
  21.         Console.WriteLine("The uploading process is complete.");
  22.         Console.ReadLine();
  23.     }
  24.     static string accessToken = "";
  25.     // static string base_url = "http://localhost:8000/api/v2/";
  26.     static string base_url = "https://api2.neurabot.ai/api/v2/";
  27.     static async Task Login(string email, string password)
  28.     {
  29.         string url = base_url +"auth/login/";
  30.         var payload = new Dictionary<string, object>
  31.         {
  32.             ["email"] = email,
  33.             ["password"] = password
  34.         };
  35.         var payloadJson = JsonConvert.SerializeObject(payload);
  36.         var content = new StringContent(payloadJson, Encoding.UTF8, "application/json");
  37.         var request = new HttpRequestMessage(HttpMethod.Post, url);
  38.         request.Content = content;
  39.         //if (!string.IsNullOrEmpty(accessToken))
  40.         //    request.Headers.Add("Authorization", "Token " + accessToken);
  41.  
  42.         using (HttpClient httpClient = new HttpClient())
  43.         {
  44.             var response = await httpClient.SendAsync(request);
  45.  
  46.             var responseString = await response.Content.ReadAsStringAsync();
  47.             if (!response.IsSuccessStatusCode)
  48.             {
  49.                 Console.WriteLine("Login Failed");
  50.             }
  51.  
  52.             dynamic jsonResponse = JsonConvert.DeserializeObject(responseString);
  53.             accessToken = jsonResponse.data.access_token;
  54.             if (!string.IsNullOrEmpty(accessToken)) { Console.WriteLine("Logged in!"); }
  55.         }
  56.     }
  57.     static async Task UploadFile(string filePath)
  58.     {
  59.         string fileName = Path.GetFileName(filePath);
  60.         long chunkSize = 5000000; // Ukuran chunk (dalam byte)
  61.  
  62.         string uploadID = "";
  63.         string endPoint = base_url + "slides/chunks/"; //endpoint for chunk file
  64.         string endPointUpload = base_url + "slides/upload/dzi/"; //endpoint for complate upload file dzi
  65.         string securityToken = accessToken;
  66.         Console.WriteLine("Security Token : " + securityToken);
  67.  
  68.         using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  69.         {
  70.             using (HttpClient httpClient = new HttpClient())
  71.             {
  72.                 httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Token", securityToken);
  73.  
  74.                 int offset = 0;
  75.                 long fileSize = fileStream.Length;
  76.                 long bytesToRead = fileSize;
  77.                 int numChunks = (int)(fileSize / chunkSize);
  78.                 long remainingBytes = fileSize % chunkSize;
  79.                 Console.WriteLine("File Size : " + fileSize);
  80.                 if (remainingBytes > 0)
  81.                     numChunks++;
  82.  
  83.                 for (int chunkIndex = 0; chunkIndex < numChunks; chunkIndex++)
  84.                 {
  85.                     long currentChunkSize = (chunkIndex == numChunks - 1 && remainingBytes > 0) ? remainingBytes : chunkSize;
  86.                     Console.WriteLine("Current Chunk Size : " + currentChunkSize);
  87.                     byte[] buffer = new byte[currentChunkSize];
  88.                     Console.WriteLine("Offset : " + offset);
  89.                     Console.WriteLine("Buffer : " + buffer.Length);
  90.                     long seek = fileStream.Seek(offset, SeekOrigin.Begin);
  91.                     int bytesRead = fileStream.Read(buffer, 0, (int)currentChunkSize);
  92.  
  93.  
  94.                     string contentRange = $"bytes {offset}-{offset + (int)currentChunkSize - 1}/{fileSize}";
  95.  
  96.                     ByteArrayContent byteContent = new ByteArrayContent(buffer);
  97.  
  98.                     MultipartFormDataContent formData = new MultipartFormDataContent();
  99.                     formData.Add(byteContent, "the_file", fileName);
  100.                     formData.Headers.Add("Content-Range", contentRange);
  101.                     formData.Headers.Add("X-Requested-With", "XMLHttpRequest");
  102.  
  103.                     if (chunkIndex > 0)
  104.                     {
  105.                         formData.Add(new StringContent(uploadID), "upload_id");
  106.                     }
  107.  
  108.                     HttpResponseMessage response = await httpClient.PostAsync(endPoint, formData);
  109.                     var responseContent = await response.Content.ReadAsStringAsync();
  110.                     var responseObject = JsonConvert.DeserializeObject<dynamic>(responseContent);
  111.                     Console.WriteLine("===============");
  112.  
  113.                     if (response.IsSuccessStatusCode)
  114.                     {
  115.                         if (chunkIndex == 0)
  116.                         {
  117.                             uploadID = responseObject.upload_id;
  118.                         }
  119.                         //offset = Convert.ToInt32(responseObject.offset);
  120.  
  121.                         bytesToRead -= bytesRead;
  122.                         Console.WriteLine(responseObject);
  123.                         Console.WriteLine($"Chunk {chunkIndex + 1}/{numChunks} uploaded successfully.");
  124.                     }
  125.                     else
  126.                     {
  127.                         Console.WriteLine(responseObject);
  128.                         Console.WriteLine($"Failed to upload chunk {chunkIndex + 1}/{numChunks}. Status: {response.StatusCode}");
  129.                     }
  130.                     offset += bytesRead;
  131.                 }
  132.  
  133.                 if (uploadID != "")
  134.                 {
  135.                     var payload = new Dictionary<string, object>{
  136.                         { "upload_id", $"{uploadID}"},
  137.                         //{"lab_id", 18233} //optional
  138.                     };
  139.                     string jsonPayload = JsonConvert.SerializeObject(payload);
  140.                     HttpContent content = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
  141.                     HttpResponseMessage response_upload = await httpClient.PostAsync(endPointUpload, content);
  142.                     var content_response = await response_upload.Content.ReadAsStringAsync();
  143.                     Console.WriteLine(content_response);
  144.  
  145.                 }
  146.             }
  147.         }
  148.     }
  149.  
  150. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement