form表单上传文件
<form action="/upload/" method="post" enctype="multipart/form-data">
头像: <input type="file" name="head-pic">
用户名: <input type="text" name="username">
<input type="submit">
</form>
views:
def upload(request):
if request.method=="GET":
return render(request,\'upload.html\')
else:
print(request.POST) #拿到的是post请求的数据,但是文件相关数据需要用request.FELES去拿
print(request.FILES)
#<MultiValueDict: \'head-pic\': [<InMemoryUploadedFile: p2.jpg (image/jpeg)>]>
file_obj=request.FILES.get(\'head-pic\')
print(file_obj)
print(file_obj.name)
file_name=file_obj.name
import os
path=os.path.join(settings.BASE_DIR,\'static\',\'img\',file_name)
with open(path,\'wb\') as f:
for i in file_obj:
f.write(i)
# f=open(\'xx.txt\',\'rb\')
# with open(\'xx.txt\',\'wb\') as f2:
# for i in f:
# f2.write(i)
return HttpResponse(\'ok\')
文件上传
在settings.py
中配置文件上传的路径
#上文件的目录
MEDIA_URL = \'/media/\'
MEDIA_ROOT = os.path.join(BASE_DIR,\'media\')
from django.contrib import admin
from django.urls import path, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path(\'admin/\', admin.site.urls),
path(\'upload/\', include(\'upload_app.urls\')),
]
#文件上传的路径
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
三、代码编写
以下代码都在uoload_app
目录下
3.1、models.py
这里的模型文件的picture会直接映射图片上传的相对位置
from django.db import models
# Create your models here.
class Content(models.Model):
title = models.FileField(\'文章名称\',max_length=11)
picture = models.FileField(upload_to=\'picture\')
3.2、views.py
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
#上传文件
from upload_app.models import Content
def test_upload(request):
if request.method == \'GET\':
return render(request, \'upload_app/test_upload.html\')
elif request.method == \'POST\':
title = request.POST[\'title\']
myfile = request.FILES[\'myfile\']
Content.objects.create(title=title,picture=myfile)
return HttpResponse(\'----上传成功!\')
3.3、urls.py
from django.urls import path
from . import views
urlpatterns = [
path(\'upload\', views.test_upload),
]
form.html
<form action="" method="post" enctype="multipart/form-data">
% csrf_token %
<p><input type="text" name="title"></p>
<p> <input type="file" name="myfile"></p>
<p><input type="submit"></p>
</form>
<form action="" method="post" enctype="multipart/form-data">
% csrf_token %
<p><input type="text" name="title"></p>
<p> <input type="file" name="myfile"></p>
<p><input type="submit"></p>
</form>
项目中最近有用到表单提交,是带有图片上传的表单录入,需要ajax异步提交,网上找了好多例子都是只能提交上传字段一个信息的,这里整理一下。表单里有普通文本信息字段也有图片上传字段。
1、jsp代码--引入jquery和jquery.form.js
<script type="text/javascript" src="<%=basePath %>js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="<%=basePath %>js/jquery.form.js"></script>
<!--form表单,异步提交一定使用submit按钮,form配置如下-->
<form id="userForm" method="post" action="" enctype="multipart/form-data" class="bl-form bl-formhor fl">
<table>
<tr>
<td class="Taa"><label for="enterpriseName">*企业名称:</label></td>
<td class="Tbb"><input type="text" name="enterpriseName" id="enterpriseName" readOnly class="inp1"/></td>
</tr>
<tr>
<td class="Taa">身份证图片:</td>
<td><a href="javascript:;" class="btn btn2 a_uplaod"><input type="file" name="identitypic" id="pic" onchange="javascript:setImagePreview();">上传图片</a></td>
</tr>
</table>
<input type="button" value="确认升级" class="mg btn btn2 d2-5" onclick="ajaxSubmitForm();"/>
<input type="button" value="清除" class=" btn btn2 d2-5" onclick="resetForm();"/>
</form>
2、javascript代码
function ajaxSubmitForm() {
var option = {
url : ‘${pageContext.request.contextPath}/userController/upgradeUser_form‘,
type : ‘POST‘,
dataType : ‘json‘,
headers : {"ClientCallMode" : "ajax"}, //添加请求头部
success : function(data) {
if("success"==data.resultMessage){
alert("个人用户已成功升级为企业用户!");
}
else{
alert("企业用户升级失败,请联系管理员!");
return;
}
},
error: function(data) {
alert("企业用户升级失败,请联系管理员!");
}
};
$("#userForm").ajaxSubmit(option);
return false; //最好返回false,因为如果按钮类型是submit,则表单自己又会提交一次;返回false阻止表单再次提交
}