Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
PhilippMDoerner opened this issue Jan 22, 2022 · 0 comments
Labels
enhancement New feature or request

Comments

@PhilippMDoerner
Copy link
Contributor

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
@ringabout ringabout added the enhancement New feature or request label Jan 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants