赞
踩
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
url(r'^media/(?P<path>.*)$', serve, {'document_root': MEDIA_ROOT}, name='media'),
# 完整的urls
from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include
from django.views.static import serve
from mytest01.settings import MEDIA_ROOT
urlpatterns = [
path('admin/', admin.site.urls),
path('api/',include("myapp01.urls")),
url(r'^media/(?P<path>.*)$', serve, {'document_root': MEDIA_ROOT}, name='media'),
]
from django.urls import path
from myapp01 import views
urlpatterns = [
path('upload/',views.UploadFile)
]
def UploadFile(request):
data = {}
if request.method == "POST":
upload_file = request.FILES.get("uploadfile")
file_name = os.path.splitext(upload_file.name)
print(file_name)
print(upload_file.name)
print(upload_file.size)
# FileSystemStorage类继承自Storage类,location是存储文件的绝对路径,默认值是
# settings中的MEDIA_ROOT值,base_url默认值是settings中的MEDIA_URL值。
fs = FileSystemStorage()
filename = fs.save(upload_file.name, upload_file)
data = {
"file_data": "http://127.0.0.1:8001" + str(fs.url(filename))}
return render(request, 'upload.html', context=data)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>Upload</h2>
<form method="post" enctype = "multipart/form-data">
<input type="file" name="uploadfile">
<button type="submit">upload file</button>
</form>
<h1><a href="{{ file_data }}">download</a></h1>
</body>
</html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。