-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.go
102 lines (82 loc) · 2.12 KB
/
upload.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"bytes"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"strconv"
"github.com/joho/godotenv"
)
func UploadPDF(fileName string) {
err := godotenv.Load()
if err != nil {
fmt.Println("Error loading .env file:", err)
return
}
// Set the URL for uploading the file
uploadURL := "https://graph.microsoft.com/v1.0/me/drive/root:/FILE" + strconv.Itoa(fileCount) + ".pdf:/content"
fileCount++
// Open the PDF file
file, err := os.Open(fileName)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
// Read the file content
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println("Error reading file:", err)
return
}
// Create a new multipart form
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Create a new file part
part, err := writer.CreateFormFile("file", "FILE_NAME.pdf")
if err != nil {
fmt.Println("Error creating form file:", err)
return
}
// Write the file content to the file part
_, err = part.Write(fileBytes)
if err != nil {
fmt.Println("Error writing file part:", err)
return
}
// Close the multipart form
writer.Close()
// Create a new HTTP request with the multipart form data
req, err := http.NewRequest("PUT", uploadURL, body)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set the access token in the request header
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", writer.FormDataContentType())
// Send the HTTP request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Check the response status code
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
fmt.Println("Error uploading file: HTTP status", resp.StatusCode)
//print the error
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
}
bodyString := string(bodyBytes)
fmt.Println(bodyString)
return
}
// Print the upload success message
fmt.Println("File uploaded successfully!")
}