当前位置: 移动技术网 > IT编程>脚本编程>Python > 在Django中接收文件并存储

在Django中接收文件并存储

2019年03月04日  | 移动技术网IT编程  | 我要评论

暗夜的吸血情人,威东航运有限公司,促销信息

首先是一个views函数的例子

def get_user_profiles(request):
    if request.method == 'post':
            myfile = request.files.get("filename", none)
            if myfile:
                dir = os.path.join(os.path.join(base_dir, 'static'),'profiles')
                destination = open(os.path.join(dir, myfile.name),
                                   'wb+')
                for chunk in myfile.chunks():
                    destination.write(chunk)
                destination.close()
            return httpresponse('ok')

这是一个简单的接收客户端上传的头像文件并保存的例子,应该看过这个就已经大体会使用接收文件了

但是这里的filename是客户端上传的文件名,也可能是像下面这样的表单

<input type="file" name="filename" />

如果不知道固定上传的文件名,想要客户端上传什么文件就以其上传的名字命名可以这么写

def get_user_profiles(request):
    if request.method == 'post':
        if request.files:
            myfile =none
            for i in request.files:
                myfile = request.files[i]
            if myfile:
                dir = os.path.join(os.path.join(base_dir, 'static'),'profiles')
                destination = open(os.path.join(dir, myfile.name),
                                   'wb+')
                for chunk in myfile.chunks():
                    destination.write(chunk)
                destination.close()
            return httpresponse('ok')

不过这个是通过输出request.files试出来的,不知道是否有更合适的方法。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网