使用django将文件复制到另一个文件夹中?

时间:2017-12-29 22:00:23

标签: python django file-upload image-upload django-file-upload

我需要将个人资料图片上传到Django的不同文件夹中。因此,我为每个帐户都有一个文件夹,并且配置文件图像必须转到特定文件夹。我怎么能这样做?

这是我的 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')

2 个答案:

答案 0 :(得分:2)

您可以将可调用对象传递给upload_to。基本上,它意味着可调用返回的任何值,图像将被上传到该路径中。

示例:

def get_upload_path(instance, filename):
    return "%s/%s" % (instance.user.id, filename)

class MyModel:
    user = ...
    image = models.FileField(upload_to=get_upload_path)

docs中还有更多信息,也是一个例子,尽管与我上面发布的相似。

答案 1 :(得分:0)

通过查看Django docs执行img = request.FILES['avatar']时得到的内容,您会得到一个文件描述符,指向包含图片的打开文件。

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

#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')

注意:代码未经测试。