]> BookStack Code Mirror - api-scripts/blob - dotnet-upload-attachment/BookStackConsole/Program.cs
Added powershell-files-to-pages example
[api-scripts] / dotnet-upload-attachment / BookStackConsole / Program.cs
1 using System;
2 using System.IO;
3 using System.Net;
4 using System.Net.Http;
5
6 namespace BookStackConsole
7 {
8     class Program
9     {
10         static void Main(string[] args)
11         {
12             // Check expected command arguments have been passed
13             if (args.Length < 2)
14             {
15                 Console.Error.WriteLine("Both <page_id> and <file_path> need to be provided!");
16                 Environment.Exit(1);
17             }
18             
19             // Get our BookStack details from the environment
20             var baseUrl = Environment.GetEnvironmentVariable("BS_URL") ?? "";
21             var tokenId = Environment.GetEnvironmentVariable("BS_TOKEN_ID") ?? "";
22             var tokenSecret = Environment.GetEnvironmentVariable("BS_TOKEN_SECRET") ?? "";
23             baseUrl = baseUrl.TrimEnd('/');
24             Console.WriteLine("base: " + baseUrl);
25
26             // Get our target page ID and file path from command args.
27             var pageId = args[0];
28             var filePath = args[1];
29
30             // Check our file exists
31             if (!File.Exists(filePath))
32             {
33                 Console.Error.WriteLine("Both <page_id> and <file_path> need to be provided!");
34                 Environment.Exit(1);
35             }
36             
37             // Get our file name and read stream
38             var fileName = Path.GetFileName(filePath);
39             var fileStream = File.OpenRead(filePath);
40             
41             // Format our post data
42             var postData = new MultipartFormDataContent();
43             postData.Add(new StringContent(pageId), "uploaded_to");
44             postData.Add(new StringContent(fileName), "name");
45             postData.Add(new StreamContent(fileStream), "file", fileName);
46
47             // Attempt to send up our file
48             var client = new HttpClient();
49             client.DefaultRequestHeaders.Add("Authorization", $"Token {tokenId}:{tokenSecret}");
50             var respMessage = client.PostAsync(baseUrl + "/api/attachments", postData);
51             
52             // Write out a message to show success/failure along with response data
53             Console.WriteLine("Response: " + respMessage.Result.Content.ReadAsStringAsync().Result);
54             if (respMessage.IsCompletedSuccessfully && respMessage.Result.StatusCode == HttpStatusCode.OK)
55             {
56                 Console.WriteLine("Attachment uploaded successfully!");
57                 Environment.Exit(0);
58             }
59             
60             Console.WriteLine("Attachment failed to upload!");
61             Environment.Exit(1);
62         }
63     }
64 }