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>
标签:jquery,form,request,upload,表单,path,import,django,上传 From: https://www.cnblogs.com/mengdie1978/p/17342696.html