uploadOne一次上传一个文件
0.写在前面:
上传文件的亮点强制要求:
- The HTML form to have the attribute enctype="multipart/form-data" set correctly.
- The form must be submitted using the POST method.
Django have proper model fields to handle uploaded files: FileField and ImageField.
The files uploaded to FileField or ImageField are not stored in the database but in the filesystem.
FileField and ImageField are created as a string field in the database (usually VARCHAR), containing the reference to the actual file.
If you delete a model instance containing FileField or ImageField, Django will not delete the physical file, but only the reference to the file.
The request.FILES is a dictionary-like object. Each key in request.FILES is the name from the <input type="file" name="" />.Each value in request.FILES is an UploadedFile instance.
基本settings.py配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'UploadOne', #一次一个文件的应用
#'UploadMulti', #一次多个文件的应用,下节说
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR,'templates'), #模板文件的搜索路径之一,一般放些公共模板
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media', #to access the MEDIA_URL in template
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #熟悉用Myslq
'NAME': 'uploadFiles',
'HOST':'127.0.0.1',
'PORT':'3306',
'USER':'root',
'PASSWORD':'xxxxxxxx',
}
}
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"), #static文件的搜索路径之一,一般放些公共静态代码
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'staticRoot') #collectstatic执行后
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media') #上传文件所在的目录
项目名uploadFiles所在路径是'/root/suyn_website',在项目下创建static、staticRoot、media、templates几个文件夹,用于后续放静态文件、上传文件、模板文件。
应用UploadOne,文件夹树:
root@ubuntu:~/suyn_website/uploadFiles# tree
.
├── manage.py
├── media
│ ├── documents
│ ├── mount_IPPe45v.sh
│ ├── mount.sh
├── static
├── staticRoot
├── templates
├── uploadFiles
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
└── UploadOne
├── admin.py
├── apps.py
├── forms.py
├── __init__.py
├── migrations
│ ├── 0001_initial.py
│ ├── 0001_initial.pyc
│ ├── __init__.py
│ └── __init__.pyc
├── models.py
├── templates
│ └── UploadOne
│ ├── home.html
│ ├── base.html
│ ├── model_form_upload.html
│ └── simple_upload.html
├── tests.py
├── urls.py
└── views.py
1. home主页有两个链接,分别向服务器发送请求,针对两种文件上传方式。
# urls.py
from django.conf.urls import url
from . import views
app_name = 'UploadOne'
urlpatterns = [
url(r'^$', views.home, name='home'),
]
# views.py
from django.shortcuts import render,redirect
from uploadFiles import settings
from django.core.files.storage import FileSystemStorage
from .models import Document
from .forms import DocumentForm
def home(request):
documents = Document.objects.all()
return render(request, 'UploadOne/home.html', { 'documents': documents })
# templates/UploadOne/base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple File Upload</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
# templates/UploadOne/home.html
{% extends 'UploadOne/base.html' %}
{% block content %}
<ul>
<li> #第一种文件传递方式
<a href="{% url 'UploadOne:simple_upload' %}">Simple Upload</a>
</li>
<li> #第二种文件传递方式
<a href="{% url 'UploadOne:model_form_upload' %}">Model Form Upload</a>
</li>
</ul>
<p>Uploaded files:</p> #将上传了的文件参考路径列出来
<ul>
{% for obj in documents %}
<li>
<a href="{{ obj.document.url }}">{{ obj.document.name }}</a>
<small>(Uploaded at: {{ obj.uploaded_at }})</small>
</li>
{% endfor %}
</ul>
{% endblock %}
2.两种文件传递方式:simple_upload VS. model_form_upload
# urls.py
url(r'^simple_upload/$',views.simple_upload,name='simple_upload'),
url(r'^model_form_upload/$', views.model_form_upload, name='model_form_upload'),
# views.py ### a minimal file upload example using FileSystemStorage
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile) #最基本的文件传递方式
uploaded_file_url = fs.url(filename)
return render(request, 'UploadOne/simple_upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'UploadOne/simple_upload.html')
# templates/UploadOne/simple_upload
{% extends 'UploadOne/base.html' %}
{% load static %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile"><br>
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
{% endif %}
<p><a href="{% url 'UploadOne:home' %}">Return to home</a></p>
{% endblock %}
# views.py
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('UploadOne:home')
else:
form = DocumentForm()
return render(request, 'UploadOne/model_form_upload.html', {
'form': form
})
# templates/UploadOne/model_form_upload.html
{% extends 'UploadOne/base.html' %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<p><a href="{% url 'UploadOne:home' %}">Return to home</a></p>
{% endblock %}