使用django将文件复制到另一个文件夹吗? [英] Copy file into another folder with django?

查看:436
本文介绍了使用django将文件复制到另一个文件夹吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将个人资料图片上传到Django中的不同文件夹中.因此,我为每个帐户都有一个文件夹,个人资料图像必须转到特定的文件夹.我该怎么办?

I need to upload profile images into diferent folders in Django. So, I have a folder for each account, and the profile image have to go to the specific folder. How can I do that?

这是我的 uploadprofile.html

<form action="{% url 'uploadimage' %}" enctype="multipart/form-data" method="POST">
  {% csrf_token %}
  <input type="file" name="avatar" accept="image/gif, image/jpeg, image/png">
  <button type="submit">Upload</button>
</form>

这是我在 views.py

def uploadimage(request):
    img = request.FILES['avatar'] #Here I get the file name, THIS WORKS

    #Here is where I create the folder to the specified profile using the user id, THIS WORKS TOO
    if not os.path.exists('static/profile/' + str(request.session['user_id'])):
        os.mkdir('static/profile/' + str(request.session['user_id']))


    #Here is where I create the name of the path to save as a VARCHAR field, THIS WORKS TOO
    avatar = "../../static/profile/" + str(request.session['user_id']) + "/" + str(img)

    #THEN I HAVE TO COPY THE FILE IN img TO THE CREATED FOLDER

    return redirect(request, 'myapp/upload.html')

推荐答案

通过查看 Django文档 img = request.FILES['avatar']执行时会得到什么,您将得到一个文件描述符,该文件指向带有图像的打开文件.

By looking at Django docs what you get when you do img = request.FILES['avatar'] you get a file descriptor that points to an open file with your image.

然后您应该将内容转储到实际的avatar路径中,对吧?

Then you should to dump the contents in your actual avatar path, right?

#Here is where I create the name of the path to save as a VARCHAR field, THIS WORKS TOO
avatar = "../../static/profile/" + str(request.session['user_id']) + "/" + str(img)
# # # # # 
with open(avatar, 'wb') as actual_file:
    actual_file.write(img.read())
# # # # #    
return redirect(request, 'myapp/upload.html')

当心:该代码未经测试.

Beware: the code is untested.

这篇关于使用django将文件复制到另一个文件夹吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆