prologue icon indicating copy to clipboard operation
prologue copied to clipboard

[FeatureRequest] When using `UpLoadFile.save` and file already exists, rename file

Open PhilippMDoerner opened this issue 2 years ago • 0 comments

Heyho, I just stumbled over this while implementing file upload in my web-application:

Django has a very neat convenience functionality, which, if you try to upload a file into a directory and a file with that name already exists in there, it appends random character's between the file name and its extension in order to avoid overwriting a file that already exists.

I wanted to bring up the idea of whether it might be sensible to extend the save function in context.nim to do something similar. However, I'm not 100% convinced it would actually be a good fit for the framework since, while it is useful, it also is something that might not fit into a vision if prologue is desired to remain slim and uncomplicated. That's partially what I wanted to discuss by opening this issue.

Either way, right now I have implemented it myself like this:

import prologue
import ../applicationSettings #Provides constants for me, such as MEDIA_ROOT
import std/os

type FileNotFoundError* = object of IOError
type FileAlreadyExists* = object of IOError


proc randomString(length: int): string =
    for _ in 0..length:
        add(result, char(rand(int('A') .. int('z'))))


proc uploadArticleImage*(file: UpLoadFile): string =
  let articleImageDirectory = MEDIA_ROOT & "/article_images"
  if not dirExists(articleImageDirectory):
    raise newException(FileNotFoundError, "The article image directory '" & articleImageDirectory & "' does not exist")
  
  var filePath = articleImageDirectory & '/' & file.filename
  if fileExists(filePath):
    let (directory, name, extension) = file.filename.splitFile()
    let newFileName = name & '_' & randomString(10) & '.' & extension
    file.filename = newFileName
    filePath = articleImageDirectory & '/' & newFileName

  file.save(articleImageDirectory)
  
  result = filePath

PhilippMDoerner avatar Jan 22 '22 16:01 PhilippMDoerner