抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >


Django 带文件的表单上传

带文件的表单上传

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

enctype="multipart/form-data"

然后在 js 中添加下列代码

//选中需要上传的表单,并且进行格式化处理
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 中添加以下类

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 文件中添加如下代码

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

在 urls.py 文件中创建路由

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 函数

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

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

create database tourdb charset='utf8';
推荐阅读
Django将发布内容动态显示到页面上 Django将发布内容动态显示到页面上 Django添加新的路由 Django添加新的路由 mysql与pymysql的设置 mysql与pymysql的设置 Django中引用静态文件 Django中引用静态文件 Django的环境配置 Django的环境配置 Django Django

留言区

Are You A Robot?