SaveFile saves the file to the specified path or the default upload path if no path is specified
(fh *multipart.FileHeader, path ...string)
| 22 | // SaveFile saves the file to the specified path or the default upload path |
| 23 | // if no path is specified |
| 24 | func (c *Ctx) SaveFile(fh *multipart.FileHeader, path ...string) error { |
| 25 | var file multipart.File |
| 26 | |
| 27 | file, err := fh.Open() |
| 28 | if err != nil { |
| 29 | return err |
| 30 | } |
| 31 | defer file.Close() |
| 32 | |
| 33 | // Extract filename from header directly, which is more reliable. |
| 34 | fileName := fh.Filename |
| 35 | if fileName == "" { |
| 36 | // Attempt to retrieve the file name from the "Content-Disposition" header. |
| 37 | disposition := fh.Header.Get("Content-Disposition") |
| 38 | if disposition != "" { |
| 39 | if idx := strings.Index(disposition, "filename="); idx != -1 { |
| 40 | fileName = disposition[idx+len("filename="):] |
| 41 | fileName = strings.Trim(fileName, "\"") |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | if fileName == "" { |
| 47 | return ErrFileName |
| 48 | } |
| 49 | |
| 50 | // Strip directory components to prevent path traversal attacks. |
| 51 | fileName = filepath.Base(filepath.Clean(fileName)) |
| 52 | |
| 53 | var filePath string |
| 54 | if len(path) > 0 { |
| 55 | filePath = path[0] |
| 56 | } else { |
| 57 | filePath = filepath.Join(c.Server.config.UploadPath, fileName) |
| 58 | } |
| 59 | |
| 60 | // Create the necessary directory structure for the file path. |
| 61 | if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil { |
| 62 | return err |
| 63 | } |
| 64 | |
| 65 | // Create and write to the output file. |
| 66 | out, err := os.Create(filePath) |
| 67 | if err != nil { |
| 68 | return err |
| 69 | } |
| 70 | defer out.Close() |
| 71 | |
| 72 | // Copy file contents from the uploaded file to the destination. |
| 73 | if _, err = io.Copy(out, file); err != nil { |
| 74 | return err |
| 75 | } |
| 76 | |
| 77 | return nil |
| 78 | } |
| 79 | |
| 80 | func (c *Ctx) MultipartForm() *multipart.Form { |
| 81 | return c.Request.MultipartForm |