django上传文件是通过html中form标签实现,通过url.py路由寻址,views.py文件进行逻辑处理,保存在相对路径下
html大致格式:
1:entype="multipart/form-data"类型
2:input标签 type="file"
后台文件接收:
url.py路由找到对应的函数处理关系
url(r"upload/$", views.upload)
文件传入是class类,查看打印的接收结果:
为了获取用户上传文件名称,我们需要获取文件name值,将文件放到指定的文件夹里,代码如下:
1:获取文件是通过request.FILES["upload_file"]或者request.FILES.get("upload_file",None)方式
2:获取文件夹位置,将文件保存到自己建立的路径下,upload_file.name获取名称
3.写入文件的时候可以使用upload_file.chunk()方法
def upload(request): if request.method == "POST": upload_file = request.FILES.get("upload_file") path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "statics") if upload_file: with open(os.path.join(path, upload_file.name), "wb") as f: for line in upload_file.readlines(): f.write(line) return HttpResponse("upload finish") return render(request, "upload.html")
大概思路是这样,敲代码思路 要清晰,知道一步步是怎么走的