Django - Unique upload filenames regardless of file extension - django

I want to create unique filenames for each uploaded file (Similar to this), but regardless of the extension (ie, name.txt and name.dxf is a clash)
I'm converting files on my server (ie, ogg, wav, etc) to a particular filetype extension, ie. mp3, and then removing the original file.
This issue is if someone uploads a file with different extension but the same base name, then the conversion will override the original file.
I can obviously do a check if the target file already exists. I know Django will also generate some sort of unique identifier (appended to the uploaded filename) such as "_HVk3AIt" if there is a conflict with an exact filename match. Is this a UUID?
I originally though adding a randomly generated UUID would be a bad solution because even though 2^128 is like 4*10^38 (little chance of clash) you could technically override something eventually, but I guess you just keep checking the new proposed filename, and add secondary UUID if you've got a second collision etc.
Is this a good solution, or what is standard practise for such a problem?

Related

How safe is createuuid in a clustered environment?

The title pretty much says it all. The scenario is a user uploads a file but they could be hitting 1 of 6 servers depending on the current load at the time. We have run into a situation where the users are trying to upload files with special characters in their names. We can write a function to sanitize the file name but then we have to check that the new sanitized file name doesn't exists. My thought was to just rename the file using createuuid(). I believe the createuuid() function uses the servername as part of the algorithm if I remember correctly so if anything, the uniqueness should be 6 fold due to the 6 servers. Am I correct in this thinking?
If I remember correctly, CF uses timestamp+clock+servername.
Did you consider sanitizing the uploaded filename and just append the UUID? This appears failproof to me.

Human readable file name

Whenever I create an ImageField using a file called moon.png, Django, correctly following my configuration settings, puts the file in:
campaign/primary-banner/2015/11/25/moon.png
or
campaign/primary-banner/2015/11/25/moon_RcJ3FuD.png
And that is the value of imagefield.name, which I can show to the user, but is not really user friendly.
I would like to show the name of ImageField.name, but in a human readable format. Is it possible to extract the original file name (moon.png) from the ImageField? The workarounds that I can think of are:
add an extra field to my model to hold the human readable file name. Extra work, which I would like to avoid: DRY.
process the imagefield.name value to extract the original filename, but this seems too complex (I would need to exactly understand how django is generating the filename in the first place, to make sure I cover corner cases)
I had similar problem and solved it by creating my own subdirectry under MEDIA_ROOT, in which I made directory structure involvind the date and also some unique identifier. Then I moved my file to that final subdirectory and put the name to FileField.name. Everything works like charm - files are unique (thanks to unique directories) and the final name is exactly what i want user to see (as there is no need to rename it - no conflict is possible)
p.filename=get_filename_of_existing_file_to_be_stored()
p.originalfilename=get_how_it_should_be_named()
masterobject=MyNewMaster.objects.get(pk=some_id)
uniq_name=masterobject.make_something_unique()
new_object=MyObject()
new_object.master=masterobject
new_object.some_fields=some_values
daystr=date.today().strftime('%y-%m-%d')
directory='MyDir/%s/%s/%s/'%(daystr,masterobject.id,uniq_name)
if not os.path.exists(os.path.join(settings.MEDIA_ROOT,directory)):
os.makedirs(os.path.join(settings.MEDIA_ROOT,directory))
fname=os.path.join(directory,p.originalfilename)
os.rename(p.filename,os.path.join(settings.MEDIA_ROOT,fname))
new_object.filename = fname
new_object.save()
Now everthing works for me and no conflicts are possible and even Django seems happy with this hack and provides the correct filename and url for everything i tried to do with MyObject :)
Now I ended with path like:
MyDir/2015-11-29/12345/child_7/moon.png

How to edit text file data with c++

I have a program that create a text file of stock items, which contains detail of 'total production' , 'stock remaining' and so on. Now my question is how do I edit that text file with my program. For example if I mistake to enter a correct data (like production was 500 pieces but enter only 400) now how can I edit my file to make it correct without effecting other data.
You probably should not create a text file in the first place. Did you consider using sqlite (or indexed files à la GDBM ...) or some real database like PostgreSQL or MongoDb?
If you insist on editing programmatically a textual file, the only way is to process every line : either keep all of them in memory, or copy them (except the one you'll change) to some new file.... But there is no portable way to change the content of a file in the middle.
You might also be interested in textual serialization formats like JSON, YAML (or maybe even XML).

Is there a way for uploading file by asking user input local file path in django?

Is it possible to have a charfield in a form to ask user input a absolute file path then bound the file to Request.file object? I think this is quite routine but I cannot use forms.fileField to do this since I cannot find a argument you can input file path. I searched but seems no related posts can be found.
No, there is no way to do this, because there is no way to give a path to a browser file upload field - for very good security reasons imposed by the browsers themselves.

How do I make NSMetadataQuery see my saved documents' folders as packages?

I'm writing an app which saves and loads documents both locally and on iCloud. Locally is working fine, but I'm having a problem with iCloud.
The documents are saved as a package - the UIDocument reads and writes an NSFileWrapper which contains an image file, a thumbnail file, and an info plist. When I save the document to iCloud and then look at the files under 'Manage Storage', I see the individual files instead of the packages; and more importantly when I search for files using NSMetadataQuery it returns an NSMetadataItem for each of the individual files instead of the packages. As a result, my app doesn't realise there are any packages to load and iCloud is pretty useless.
I thought that if I set up the document type and exported the UTI correctly that the packages would be treated properly. Was that right? If so, what's the checklist for setting up a document type as a package? I have:
Added a document type
set LSTypeIsPackage to YES (I've tried string YES and bool YES)
set CFBundleTypeExtensions to an array containing one string: the file suffix
set LSHandlerRank to Owner
Exported a UTI with the same identifier
set it to conform to com.apple.package
added a UITypeTagSpecification dictionary, containing an array for the key public.filename-extension, which contains one string: the file suffix
I've also tried adding a matching Imported UTI to match the exported one, but no luck there.
What did I miss?
UPDATE: I notice that the OP in this question is seeing the behaviour I want (even though he doesn't want it) so it must be possible.
Based on this I tried removing the LSItemContentTypes from my plist, and it worked.