带文件的表单如何上传

带文件的表单上传

首先在表单form中必须要添加这个属性

1
enctype="multipart/form-data"

然后在js中添加下列代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//选中需要上传的表单,并且进行格式化处理
var formData=new FormData($("#formdata")[0]);
console.log(formData)
//获取用户名
var user=document.getElementById("username").innerHTML;
var date=new Date();
var month=date.getMonth()+1;
//把数据追加到表单
formData.append("username",user);
formData.append("date",date.getFullYear()+"-"+month+"-"+date.getDate());
formData.append("sign",date.getTime());
$.ajax({
type:"post",
url:"http://127.0.0.1:8000/tour/sendDay",
async:true,
data:formData,
timeout:5000,
dataType:"json",
cache:false, //提交表单必须增加的属性
contentType:false,
processData:false,
success:function(data){
alert(data);
console.log(data)
if(data.code == "1") {
alert("发布成功")
}
if(data.code == "2"){
alert("发布失败")
}
},
error:function(xhr,textState){
alert("请求失败!")
}
});

在models中添加以下类

1
2
3
4
5
6
7
8
class Tours(models.Model):
username = models.CharField(max_length=20)
date = models.CharField(max_length=20)
times = models.CharField(max_length=100)
desc = models.CharField(max_length=255)
photoname = models.FileField(upload_to="photo",null=True,blank=True)
musicname = models.FileField(upload_to="music",null=True,blank=True)
isDelete = models.BooleanField(default=False)

在settings.py文件中添加如下代码

1
2
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

在urls.py文件中创建路由

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.views.static import serve

from App import views
from tourdemo import settings
from tourdemo.settings import MEDIA_ROOT

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r"^tour/sendDay",views.tourSendDay),
#加载media文件需要的路由
url(r'^media/(?P<path>.*)/$', serve, {"document_root": MEDIA_ROOT}),

]

在views.py文件中添加tourSendDay函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def tourSendDay(request):
try:
tour = Tours()
username = request.POST.get("username")
tour.username = username
date = request.POST.get("date")
tour.date = date
times = request.POST.get("sign")
tour.times = times
music = request.FILES.get("music")
tour.musicname = music
img = request.FILES.get("photo")
tour.photoname = img
desc = request.POST.get("desc")
# print(desc)
tour.desc = desc
# print("desc",tour.desc)
tour.save()
tourdic = {"code":"1","id": tour.id, "photoname": tour.photoname.url, "musicname": tour.musicname.url, "times": tour.times,
"username": tour.username, "date": tour.date, "desc": tour.desc}

response = HttpResponse(json.dumps(tourdic))
except Exception as e:
print(e)
response = HttpResponse(json.dumps({"code": "2"}))

response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "*"
return response

注意若出现存储中文失败则需要在创建的的时候指定编码格式

1
create database tourdb charset='utf8';

评论