django之文件上传
upload.html
<form action="" method="post" enctype ="multipart/form-data">{%csrf_token%}
<input type="file" name='fafafa' id="file_upload">
<input type="submit" value="提交">
</form>
views.py
def uoload(request):
if request.method == "POST":
file = request.FILES.get("fafafa")
with open(file.name,'wb') as f:
for line in file.chunks()::
f.write(line)
f.close()
return HttpResponse('OK')
return render(request,'upload.html')
通过ajax提交 js代码
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
function FileUpload() {
var form_data = new FormData();
var file_info =$( '#file_upload')[0].files[0];
form_data.append('file',file_info);
//if(file_info==undefined)暂且不许要判断是否有附件
//alert('你没有选择任何文件');
//return false
$.ajax({
url:'/upload_ajax/',
type:'POST',
data: form_data,
processData: false, // tell jquery not to process the data
contentType: false, // tell jquery not to set contentType
success: function(callback) {
console.log('ok')
}
});
}</script>
views.py相关代码
def upload_ajax(request):
if request.method == 'POST':
file_obj = request.FILES.get('fafafa')
import os
f = open(os.path.join(BASE_DIR, 'static', 'pic', file_obj.name), 'wb')
print(file_obj,type(file_obj))
for chunk in file_obj.chunks():
f.write(chunk)
f.close()
return HttpResponse('OK')
通过iframe标签提交
upload.html
<div>
<form id="my_form" name="form" action="/upload_iframe/" method="POST" enctype="multipart/form-data">
<input type="text" name="user">
<input type="password" name="password">
<input type="file" name="file">
<input type="button" value="upload" onclick="UploadFile()">
</form>
<iframe id='my_iframe' name='my_iframe' src="" class="hide"></iframe>
</div>
function UploadFile() {
document.getElementById('my_iframe').onload = Testt;
document.getElementById('my_form').target = 'my_iframe';
document.getElementById('my_form').submit();
}
function Testt(ths){
var t = $("#my_iframe").contents().find("body").text();
console.log(t);
}
views.py
def upload_iframe(request):
if request.method == 'POST':
file_obj = request.FILES.get('file')
import os
f = open(os.path.join(BASE_DIR, 'static', 'pic', file_obj.name), 'wb')
print(file_obj,type(file_obj))
for chunk in file_obj.chunks():
f.write(chunk)
f.close()
return HttpResponse('OK')
django之文件上传
http://www.jcwit.com/article/157/