File upload and download in Python Web development

Source: Internet
Author: User
Tags uuid

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.