File upload and download for server under Django framework:
Import JSON
Import OS
Import UUID
def attachment_upload (Request):
"" "File Upload" ""
ret = {"Status": False, "data": {"path": "", "Name": ""}, "Summary": ""}
target = "Media/upload/avatar" # File Save path
Try
# Get File Object
File_obj = Request. Files.get ("file")
Raw_name = File_obj.name
If not file_obj:
Pass
Else
# Check that the directory does not exist if no new one exists
If not os.path.exists (Os.path.dirname (target)):
Os.makedirs (target)
file_name = str (UUID.UUID4 ())
File_path = Os.path.join (target, file_name)
With open (File_path, "WB") as F:
For chunk in File_obj.chunks (): # chuck is a chunked write file (. chunks () on a loop rather than using read () to ensure that large files do not use your system memory heavily. )
F.write (Chunk)
ret["status"] = True
ret["Data" [' path '] = File_path
ret["Data" [' name '] = Raw_name
Except Exception as E:
ret["Summary"] = str (e)
Return HttpResponse (Json.dumps (ret))
def attachment_download (Request):
"" File Download "" "
name = Request. Get.get ("name", None)
File_path = Request. get[' URL ']
def file_iterator (File_path, chunk_size=512):
With open (File_path, ' RB ') as F:
While True:
c = F.read (chunk_size)
If C:
Yield C
Else
Break
Response = Streaminghttpresponse (File_iterator (File_path))
response[' content-type '] = ' application/octet-stream '
response[' content-disposition ' = ' attachment;filename= ' {0} '. Format (Name.encode (' Utf-8 '). Decode (' iso-8859-1 '))
return response
File upload and download in Python Web development