Django File Upload Instance

Source: Internet
Author: User

Recently in the development process with the Django framework encountered uploading user avatar problem, through a multi-party search data, finally solve the problem!

1. First, add code similar to the following in the HTML template

12345 <formenctype="multipart/form-data" method="POST" action="/view/process/upload/file">    {% csrf_token %}    <input type="file" name="your_file"/>    <inputtype="submit" value="上传文件" /></form>

Here are a few things to look at:

    1. Form summary must have enctype= "Multipart/form-data" Property
    2. Form needs to be submitted by POST
    3. The Action property of the form corresponds to the function that handles upload upload logic in views
    4. Need to have csrf_token this tag, otherwise post cannot be submitted
    5. The first type of <input> is file, which is a document selector, and the Name property is important because the file object is later removed from this field

2. Next, write the CGI logic

1234567891011121314 defprocess_upload_file(request):    # 获取文件    file_obj =request.FILES.get(‘your_file‘, None)    iffile_obj ==None:        returnHttpResponse(‘file not existing in the request‘)        # 写入文件    file_name =‘temp_file-%d‘%random.randint(0,100000) # 不能使用文件名称,因为存在中文,会引起内部错误    file_full_path = os.path.join(UPLOAD_ROOT, file_name)    dest =open(file_full_path,‘wb+‘)    dest.write(    dest.close()        return render_to_response(‘upload_result.html‘,{})

The file is taken in the following way: "file_obj = Request." Files.get (' file ', None) ". The first parameter "your_file" corresponds to the first input label in the form. You can then get the file name by, and the () method gets the file contents. The uploaded file is placed in memory, so this method is only suitable for small file uploads.

Django File Upload Instance

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: 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.