Django上传文件,制作文件上传按钮,form上传文件
生活随笔
收集整理的這篇文章主要介紹了
Django上传文件,制作文件上传按钮,form上传文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Django上傳文件,制作文件上傳按鈕,form上傳文件 from django.shortcuts import render
from django.shortcuts import HttpResponse
from django import forms
from django.forms import fields
class UploadForm(forms.Form):
user = fields.CharField()
img = fields.FileField()
def upload(request):
if request.method == 'GET':
return render(request,'upload.html')
else:
# obj = UploadForm(request.POST,request.FILES)
# if obj.is_valid():
# user = obj.cleaned_data['user']
# img = obj.cleaned_data['img']
user = request.POST.get('user')
img = request.FILES.get('img')
# img是對象(文件大小,文件名稱,文件內容。。。)
print(img.name)
print(img.size)
f = open(img.name,'wb')
for line in img.chunks():
f.write(line)
f.close()
return HttpResponse('...')
---------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/uploads.html" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user" />
<div style="position: relative">
<a>NB上傳</a>
<input type="file" name="img" style="opacity: 0;position:absolute;top:0;left: 0;" />
</div>
<input type="submit" value="提交" />
</form>
</body>
</html> ? posted on 2018-02-19 12:27 思南1900 閱讀(...) 評論(...) 編輯 收藏
from django.shortcuts import HttpResponse
from django import forms
from django.forms import fields
class UploadForm(forms.Form):
user = fields.CharField()
img = fields.FileField()
def upload(request):
if request.method == 'GET':
return render(request,'upload.html')
else:
# obj = UploadForm(request.POST,request.FILES)
# if obj.is_valid():
# user = obj.cleaned_data['user']
# img = obj.cleaned_data['img']
user = request.POST.get('user')
img = request.FILES.get('img')
# img是對象(文件大小,文件名稱,文件內容。。。)
print(img.name)
print(img.size)
f = open(img.name,'wb')
for line in img.chunks():
f.write(line)
f.close()
return HttpResponse('...')
---------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/uploads.html" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user" />
<div style="position: relative">
<a>NB上傳</a>
<input type="file" name="img" style="opacity: 0;position:absolute;top:0;left: 0;" />
</div>
<input type="submit" value="提交" />
</form>
</body>
</html> ? posted on 2018-02-19 12:27 思南1900 閱讀(...) 評論(...) 編輯 收藏
轉載于:https://www.cnblogs.com/sinan1900/p/8453670.html
總結
以上是生活随笔為你收集整理的Django上传文件,制作文件上传按钮,form上传文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第四周 Access总结
- 下一篇: 第二周博客:xml