Django Processing files upload file uploads

Source: Internet
Author: User

Httprequest.files

The file object that the form uploads is stored in the Class Dictionary object request. Files, the form format needs to be Multipart/form-data

<form enctype= "Multipart/form-data" method= "post" action= "/foo/" ><input type= "file" name= "image"/>

Request. The keys in files come from the name value of the <input type= "file" Name= ""/> In the form:

Img=request. files[' image ']

Request. The values in files are all UploadedFile class file objects.

UploadedFile

UploadedFile is a class file object that has the following methods and properties:

Uploadedfile.read ()

Read the entire uploaded file data, the file is large, use caution.

Uploadedfile.multiple_chunks (Chunk_size=none)

Determine if the file is large enough, typically 2.5M

Uploadedfile.chunks (Chunk_size=none)

Returns a generator object that should be used instead of read () when Multiple_chunks () is true.

Uploadedfile.name

The name of the upload file.

Uploadedfile.size

The size of the uploaded file.

Uploadedfile.content_type

The Content_Type header when uploading a file, for example (e.g. Text/plain or application/pdf).

UPLAdedfile.charset

Coding

Storing files

When you want to store the uploaded file locally:

F=request. files[' image ']with open (' some/file/name.txt ', ' wb+ ') as destination: for    Chunk in F.chunks ():        Destination.write (Chunk)

Uploading files using form processing

You can also use Django's own form to handle uploading files.

Create a form with filefiled or imagefiled first:

# in Forms.py...from Django import Formsclass uploadfileform (forms. Form):    title = forms. Charfield (max_length=50)    file = forms. Filefield ()

Use form to process:

>>> F =uploadfileformt (request. POST, request. FILES)

View function:

From django.http import httpresponseredirectfrom django.shortcuts import render_to_responsefrom. Forms Import Uploadfileformdef Handle_uploaded_file (f):    with open (' Some/file/name.txt ', ' wb+ ') as destination: for        Chunk In F.chunks ():            Destination.write (Chunk) def upload_file (request):    if Request.method = = ' POST ':        form = Uploadfileform (Request. POST, request. FILES)        if Form.is_valid ():            handle_uploaded_file (Request. files[' file '])            return httpresponseredirect ('/success/url/')    else:        form = Uploadfileform ()    return Render_to_response (' upload.html ', {' form ': Form})
Uploading files using model processing

If you create a model with a Filefield or ImageField domain, you need to store the uploaded file in the model's Filefield domain.

For example, when using the Nicedit text editor, you need to store the uploaded files and create the model:

From django.db import Modelsclass niceditimage (models. Model):    image = Models. ImageField (upload_to= ' nicedit/%y/%m/%d ')

Create Modelform:

From Django Import Formsclass niceditimageform (forms. Modelform):    class Meta:        model = Niceditimage

View

def upload (Request):    if not request.user.is_authenticated ():        json = simplejson.dumps ({            ' success ': False,            ' errors ': {' __all__ ': ' Authentication Required '}}        Return HttpResponse (JSON, mimetype= ' Application/json ')    form = Niceditimageform (Request. POST or None, request. FILES or None)    if Form.is_valid ():        image = Form.save ()    #保存Form和Model        json = simplejson.dumps ({            ' Success ': True,            ' upload ': {'                links ': {                    ' original ': Image.image.url},                ' image ': {                    ' width ': Image.image.width,                    ' height ': image.image.height}            }        )    else:        json = Simplejson.dumps ({            ' success ': False, ' Errors ': form.errors})    Return HttpResponse (JSON, mimetype= ' Application/json ')

Of course, you can also manually store files into the model's file domain:

From django.http import httpresponseredirectfrom django.shortcuts import renderfrom. Forms import Uploadfileformfrom. Models Import modelwithfilefielddef Upload_file (Request):    if Request.method = = ' POST ':        form = Uploadfileform ( Request. POST, request. FILES)        if Form.is_valid ():            instance = Modelwithfilefield (file_field=request. files[' file '])   #保存文件到FileField域            instance.save ()            return httpresponseredirect ('/success/url/')    else:        form = Uploadfileform ()    return render (Request, ' upload.html ', {' form ': Form})
Do not use form processing

When you want to gain greater freedom, you can handle it all manually.

From django.db import Modelsclass Car (models. Model):    name = models. Charfield (max_length=255) Price    = models. Decimalfield (max_digits=5, decimal_places=2)    photo = models. ImageField (upload_to= ' cars ')

The Filefield of model has the following properties:

>>> car = Car.objects.get (name= "Chevy") >>> car.photo<imagefieldfile:chevy.jpg>>> > Car.photo.nameu ' cars/chevy.jpg ' >>> car.photo.pathu '/media/cars/chevy.jpg ' >>> Car.photo.urlu ' http://media.example.com/cars/chevy.jpg '

The model's Filefield is a file object that has an additional save () method in addition to the various methods that have the file object:

Fieldfile.save (name, content, Save=true)

Name is the storage name, and the content is an instance of file or file subclass

>>> car.photo.save (' myphoto.jpg ', content, Save=false) >>> Car.save ()

Similar to

>>> car.photo.save (' myphoto.jpg ', content, save=true)

Manual storage:

From django.core.files.base import contentfilephoto=request. Files.get (' photo ', ') if Photo:       file_content = ContentFile (Photo.read ())   #创建File对象    Car.photo.save ( Photo.name, file_content)   #保存文件到car的photo域    Car.save ()

  

  

 

Django Processing files upload file uploads

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.