Repository navigation
Expand file tree
/
Copy pathfile_upload_example.go
More file actions
293 lines (247 loc) · 8.71 KB
/
Copy pathfile_upload_example.go
File metadata and controls
293 lines (247 loc) · 8.71 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/0x113/pocketbase-go"
)
// FileUploadExample demonstrates uploading files to PocketBase collections
func FileUploadExample() {
fmt.Println("=== File Upload Example ===")
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Create client
client := SetupDemoClient("http://localhost:8090")
// Example 1: Create a record with a single file upload
fmt.Println("\n1. Creating a record with a single file...")
file1, err := os.Open("example-document.pdf")
if err != nil {
log.Printf("Failed to open file: %v (make sure the file exists)", err)
} else {
defer file1.Close()
files := []pocketbase.FileData{
{Reader: file1, Filename: "example-document.pdf"},
}
data := pocketbase.Record{
"title": "Important Document",
"description": "This document contains important information",
}
createdRecord, err := client.CreateRecordWithFiles(ctx, "documents",
pocketbase.WithFormData(data),
pocketbase.WithFileUpload("file", files))
if err != nil {
if apiErr, ok := err.(*pocketbase.APIError); ok {
log.Printf("Failed to create record: %s (Status: %d)", apiErr.Message, apiErr.Status)
} else {
log.Printf("Network error: %v", err)
}
} else {
fmt.Printf("✓ Successfully created record with file!\n")
fmt.Printf(" ID: %s\n", createdRecord["id"])
fmt.Printf(" Title: %s\n", createdRecord["title"])
if file, ok := createdRecord["file"]; ok {
fmt.Printf(" File: %s\n", file)
}
}
}
// Example 2: Create a record with multiple files
fmt.Println("\n2. Creating a record with multiple files...")
file2, err := os.Open("document1.pdf")
if err != nil {
log.Printf("Failed to open file: %v", err)
} else {
defer file2.Close()
file3, err := os.Open("document2.pdf")
if err != nil {
log.Printf("Failed to open file: %v", err)
file2.Close()
} else {
defer file3.Close()
files := []pocketbase.FileData{
{Reader: file2, Filename: "document1.pdf"},
{Reader: file3, Filename: "document2.pdf"},
}
data := pocketbase.Record{
"title": "Multiple Documents",
"description": "A collection with multiple files",
}
createdRecord, err := client.CreateRecordWithFiles(ctx, "documents",
pocketbase.WithFormData(data),
pocketbase.WithFileUpload("files", files))
if err != nil {
if apiErr, ok := err.(*pocketbase.APIError); ok {
log.Printf("Failed to create record: %s (Status: %d)", apiErr.Message, apiErr.Status)
} else {
log.Printf("Network error: %v", err)
}
} else {
fmt.Printf("✓ Successfully created record with multiple files!\n")
fmt.Printf(" ID: %s\n", createdRecord["id"])
fmt.Printf(" Title: %s\n", createdRecord["title"])
if files, ok := createdRecord["files"]; ok {
fmt.Printf(" Files: %v\n", files)
}
}
}
}
// Example 3: Update a record by replacing files
fmt.Println("\n3. Updating a record by replacing a file...")
newFile, err := os.Open("new-avatar.jpg")
if err != nil {
log.Printf("Failed to open file: %v", err)
} else {
defer newFile.Close()
files := []pocketbase.FileData{
{Reader: newFile, Filename: "new-avatar.jpg"},
}
data := pocketbase.Record{
"name": "Updated User",
}
updatedRecord, err := client.UpdateRecordWithFiles(ctx, "users", "RECORD_ID_HERE",
pocketbase.WithFormData(data),
pocketbase.WithFileUpload("avatar", files))
if err != nil {
if apiErr, ok := err.(*pocketbase.APIError); ok {
log.Printf("Failed to update record: %s (Status: %d)", apiErr.Message, apiErr.Status)
} else {
log.Printf("Network error: %v", err)
}
} else {
fmt.Printf("✓ Successfully updated record with new file!\n")
fmt.Printf(" ID: %s\n", updatedRecord["id"])
fmt.Printf(" Name: %s\n", updatedRecord["name"])
}
}
// Example 4: Append files to existing record
fmt.Println("\n4. Appending files to an existing record...")
appendFile, err := os.Open("document3.pdf")
if err != nil {
log.Printf("Failed to open file: %v", err)
} else {
defer appendFile.Close()
files := []pocketbase.FileData{
{Reader: appendFile, Filename: "document3.pdf"},
}
updatedRecord, err := client.UpdateRecordWithFiles(ctx, "documents", "RECORD_ID_HERE",
pocketbase.WithFileUpload("files", files, pocketbase.WithAppend()))
if err != nil {
if apiErr, ok := err.(*pocketbase.APIError); ok {
log.Printf("Failed to append file: %s (Status: %d)", apiErr.Message, apiErr.Status)
} else {
log.Printf("Network error: %v", err)
}
} else {
fmt.Printf("✓ Successfully appended file to record!\n")
fmt.Printf(" ID: %s\n", updatedRecord["id"])
if files, ok := updatedRecord["files"]; ok {
fmt.Printf(" Files: %v\n", files)
}
}
}
// Example 5: Delete specific files from a record
fmt.Println("\n5. Deleting specific files from a record...")
updatedRecord, err := client.UpdateRecordWithFiles(ctx, "documents", "RECORD_ID_HERE",
pocketbase.WithFileUpload("files", nil, pocketbase.WithDelete("document1.pdf", "document2.pdf")))
if err != nil {
if apiErr, ok := err.(*pocketbase.APIError); ok {
log.Printf("Failed to delete files: %s (Status: %d)", apiErr.Message, apiErr.Status)
} else {
log.Printf("Network error: %v", err)
}
} else {
fmt.Printf("✓ Successfully deleted files from record!\n")
fmt.Printf(" ID: %s\n", updatedRecord["id"])
if files, ok := updatedRecord["files"]; ok {
fmt.Printf(" Remaining files: %v\n", files)
}
}
// Example 6: Using helper functions to create FileData
fmt.Println("\n6. Using helper functions to create FileData...")
// From file path
fileData, err := pocketbase.CreateFileDataFromFile("example.txt")
if err != nil {
log.Printf("Failed to create file data from path: %v", err)
} else {
if fileReader, ok := fileData.Reader.(*os.File); ok {
defer fileReader.Close()
}
data := pocketbase.Record{
"title": "Example with Helper",
}
createdRecord, err := client.CreateRecordWithFiles(ctx, "documents",
pocketbase.WithFormData(data),
pocketbase.WithFileUpload("file", []pocketbase.FileData{fileData}))
if err != nil {
log.Printf("Failed to create record: %v", err)
} else {
fmt.Printf("✓ Successfully created record using helper function!\n")
fmt.Printf(" ID: %s\n", createdRecord["id"])
}
}
// From bytes
fileBytes := []byte("This is file content from bytes")
fileDataFromBytes := pocketbase.CreateFileDataFromBytes(fileBytes, "content.txt")
data := pocketbase.Record{
"title": "File from Bytes",
}
createdRecord, err := client.CreateRecordWithFiles(ctx, "documents",
pocketbase.WithFormData(data),
pocketbase.WithFileUpload("file", []pocketbase.FileData{fileDataFromBytes}))
if err != nil {
log.Printf("Failed to create record: %v", err)
} else {
fmt.Printf("✓ Successfully created record from byte data!\n")
fmt.Printf(" ID: %s\n", createdRecord["id"])
fmt.Printf(" Title: %s\n", createdRecord["title"])
}
fmt.Println("\n=== File Upload Examples Complete ===")
}
// FileUploadWithQueryOptionsExample demonstrates using query options with file uploads
func FileUploadWithQueryOptionsExample() {
fmt.Println("\n=== File Upload with Query Options Example ===")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
client := SetupDemoClient("http://localhost:8090")
// Create a record with files and expand related fields
file, err := os.Open("profile-picture.jpg")
if err != nil {
log.Printf("Failed to open file: %v", err)
return
}
defer file.Close()
files := []pocketbase.FileData{
{Reader: file, Filename: "profile-picture.jpg"},
}
data := pocketbase.Record{
"name": "John Doe",
"email": "john@example.com",
"department": "DEPARTMENT_ID",
}
// Create with file upload and expand department relation
createdRecord, err := client.CreateRecordWithFiles(ctx, "employees",
pocketbase.WithFormData(data),
pocketbase.WithFileUpload("photo", files),
// Note: WithExpand and WithFields work as FileUploadOptions
func(opts *pocketbase.FileUploadOptions) {
opts.Expand = []string{"department"}
opts.Fields = []string{"id", "name", "email", "photo", "department"}
})
if err != nil {
if apiErr, ok := err.(*pocketbase.APIError); ok {
log.Printf("Failed to create record: %s (Status: %d)", apiErr.Message, apiErr.Status)
} else {
log.Printf("Network error: %v", err)
}
} else {
fmt.Printf("✓ Successfully created record with expanded relations!\n")
fmt.Printf(" ID: %s\n", createdRecord["id"])
fmt.Printf(" Name: %s\n", createdRecord["name"])
if expand, ok := createdRecord["expand"]; ok {
fmt.Printf(" Expanded data: %v\n", expand)
}
}
fmt.Println("\n=== File Upload with Query Options Complete ===")
}