Replies: 1 comment 12 replies
-
Currently there is no easy way to change the uploaded file name without "hacky" workarounds. You can get the original file name by reading the MultipartForm data after record creation, but you'll also have to rename the uploaded file and this currently can be done only if you use the local filesystem (the filesystem abstraction doesn't support renaming file keys; I'll consider updating it in the future). Here is a short example (I haven't tested it!): app.OnRecordAfterCreateRequest().Add(func(e *core.RecordCreateEvent) error {
_, fh, _ := e.HttpContext.Request().FormFile("yourFileField")
customFileName := fh.Filename // eventually do some normalizations...
oldFileName := e.Record.GetString("yourFileField")
e.Record.Set("yourFileField", customFileName)
if err := app.Dao().SaveRecord(e.Record); err != nil {
return err
}
// Rename the uploaded file in the local storage dir
//
// NB! There are no security checks for path traversal!
oldFilePath := filepath.Join(app.DataDir(), "storage", e.Record.BaseFilesPath(), oldFileName)
newFilePath := filepath.Join(app.DataDir(), "storage", e.Record.BaseFilesPath(), customFileName)
os.Rename(oldFilePath, newFilePath)
return nil
}) It depends on your use case, but in general I'd recommend NOT allowing custom upload filenames, because you also will have to take care for sanitizing the user input and making sure that the final path format is supported on the targeted platform (eg. has less than 256 chars; for a list with all filesystem limitations you could check https://en.wikipedia.org/wiki/Comparison_of_file_systems#Limits). If you want to just show a human readable uploaded filename to the end user, you can define a custom text field (eg. app.OnRecordBeforeCreateRequest().Add(func(e *core.RecordCreateEvent) error {
_, fh, _ := e.HttpContext.Request().FormFile("yourFileField")
// auto store the original uploaded filename (if not explicitly set)
//
// we don't need to explicitly call save because the finalizer
// of the before event hook will do it for us
if e.Record.GetString("filename") != "" {
e.Record.Set("filename", fh.Filename)
}
return nil
}) |
Beta Was this translation helpful? Give feedback.
-
Hello! How i can get name uploaded files during record creation? I need save original file name, if file name is not the Latin alphabet, but for example Chinese characters or Cyrillic, a new filename is generated.
I think I can update the collection after uploading, but I can't find out the original filename.
Beta Was this translation helpful? Give feedback.
All reactions