|
1 | 1 | package directadmin |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "bytes" |
4 | 5 | "fmt" |
5 | 6 | "io" |
| 7 | + "mime/multipart" |
6 | 8 | "net/http" |
7 | 9 | "net/url" |
8 | 10 | "os" |
@@ -75,7 +77,7 @@ func (c *UserContext) DownloadFileToDisk(filePath string, outputPath string) err |
75 | 77 | return err |
76 | 78 | } |
77 | 79 |
|
78 | | - return os.WriteFile(outputPath, response, 0644) |
| 80 | + return os.WriteFile(outputPath, response, 0o644) |
79 | 81 | } |
80 | 82 |
|
81 | 83 | // ExtractFile unzips the given file path on the server |
@@ -108,14 +110,31 @@ func (c *UserContext) ExtractFile(filePath string, file string) error { |
108 | 110 | return nil |
109 | 111 | } |
110 | 112 |
|
111 | | -// UploadFile (user) uploads the provided byte data as a file for the session user |
| 113 | +// UploadFile uploads the provided byte data as a file for the session user |
112 | 114 | func (c *UserContext) UploadFile(uploadToPath string, fileData []byte) error { |
113 | | - // add / to the beginning of uploadToPath if it doesn't exist |
| 115 | + // Add / to the beginning of uploadToPath if it doesn't exist. |
114 | 116 | if uploadToPath[0] != '/' { |
115 | 117 | uploadToPath = "/" + uploadToPath |
116 | 118 | } |
117 | 119 |
|
118 | | - if _, err := c.uploadFile(http.MethodPost, "/api/filemanager/upload?path="+uploadToPath, fileData, nil, "application/json"); err != nil { |
| 120 | + body := &bytes.Buffer{} |
| 121 | + writer := multipart.NewWriter(body) |
| 122 | + |
| 123 | + part, err := writer.CreateFormFile("file", filepath.Base(uploadToPath)) |
| 124 | + if err != nil { |
| 125 | + return fmt.Errorf("creating form file: %w", err) |
| 126 | + } |
| 127 | + |
| 128 | + if _, err = part.Write(fileData); err != nil { |
| 129 | + return fmt.Errorf("writing file data: %w", err) |
| 130 | + } |
| 131 | + |
| 132 | + if err = writer.Close(); err != nil { |
| 133 | + return fmt.Errorf("finalizing form data: %w", err) |
| 134 | + } |
| 135 | + |
| 136 | + // Now use this content type which includes the boundary. |
| 137 | + if _, err = c.uploadFile(http.MethodPost, "/api/filemanager/upload?dir="+filepath.Dir(uploadToPath)+"&name="+filepath.Base(uploadToPath), body.Bytes(), nil, writer.FormDataContentType()); err != nil { |
119 | 138 | return err |
120 | 139 | } |
121 | 140 |
|
|
0 commit comments