創(chuàng)建Django工程與應(yīng)用
在進(jìn)行Django文件上傳的實(shí)例之前,首先需要通過(guò)以下命令在命令行中創(chuàng)建Django工程,并在工程內(nèi)創(chuàng)建應(yīng)用:
```bash
django-admin start
                        
                        
                        
                        
                        
                         創(chuàng)建Django工程與應(yīng)用
在進(jìn)行Django文件上傳的實(shí)例之前,首先需要通過(guò)以下命令在命令行中創(chuàng)建Django工程,并在工程內(nèi)創(chuàng)建應(yīng)用:
```bash
django-admin startproject djfileup
cd djfileup
python  startapp myfile
```
 配置工程設(shè)置
使用PyCharm打開工程后,在工程根目錄的`djfileup`的``文件中,添加應(yīng)用和模板路徑的設(shè)置。具體添加內(nèi)容如下:
```python
INSTALLED_APPS  [
    '',
    '',
    '',
    '',
    '',
    '',
    '',
]
TEMPLATES  [
    {
        'BACKEND': '',
        'DIRS': [('templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                '_',
                '_',
                '_',
                '_',
            ],
        },
    },
]
```
 編寫HTML文件
在工程根目錄新建`templates`文件夾,在該文件夾內(nèi)新建``文件,并編寫如下代碼:
```html
    
    file
    
```
注意:`enctype`一定要設(shè)置為`multipart/form-data`。
 配置URL路由
在工程根目錄的`djfileup`文件夾的``中包含應(yīng)用的路由,配置文件內(nèi)容如下:
```python
from  import url, include
from  import admin
urlpatterns  [
    url(r'^admin/', ),
    url(r'^', include('myfile.urls')),
]
```
 編寫應(yīng)用的URL與視圖函數(shù)
在應(yīng)用目錄內(nèi),新建``文件,并編寫代碼指向視圖函數(shù),示例代碼如下:
```python
from  import url
from . import views
urlpatterns  [
    url(r'^fileup/', ),
]
```
 處理文件上傳的視圖函數(shù)
在應(yīng)用的``文件中編寫處理圖片文件上傳的視圖函數(shù),具體代碼如下:
```python
from  import render, HttpResponse
def fileup(request):
    if   'POST':
        file  ('file', None)
        if file:
            with open('', 'wb') as f:
                for chunk in ():
                    f.write(chunk)
            return HttpResponse('ok')
    return render(request, '')
```
 測(cè)試文件上傳
運(yùn)行服務(wù)器并測(cè)試文件上傳功能:
```bash
python  runserver
```
點(diǎn)擊提交后,會(huì)在工程根目錄創(chuàng)建``文件,表示已成功接收到上傳的圖片。