django文件上传
views.py
from django.shortcuts import render,HttpResponse import random from upload import settings # Create your views here. # def upload(request): # if request.method == "POST": # file_obj = request.FILES.get("upload") # print(file_obj.name,) # with open(file_obj.name,'wb') as f: # for line in file_obj.chunks(): # f.write(line) # return HttpResponse("上传成功") # return render(request,"upload.html") def upload(request): if request.method == "POST": file_obj = request.FILES.get("upload") print(file_obj.name) # file_name = file_obj.name.rsplit(".",maxsplit=1)[0] + str(random.randint(0,100000))+'.'+file_obj.name.rsplit(".",maxsplit=1)[1] # print(file_name)#存在static/media/img文件夹下 fname = '%s/img/%s' % (settings.MEDIA_ROOT, file_obj.name) with open(fname,'wb') as f: for line in file_obj.chunks(): f.write(line) return HttpResponse("上传成功") return render(request,"upload.html")
upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} <span>文件上传:</span> <input type="file" name="upload"> <input type="submit" value="提交"> </form> </body> </html>
setting.py
MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")
存在static/media/img文件夹下
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步