Skip to main content
 首页 » 编程设计

python之使用 Django 将文件复制到另一个文件夹

2024年08月19日28lovecherry

我需要将个人资料图片上传到 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

中的 View
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') 

请您参考如下方法:

您可以将可调用对象传递给 upload_to。基本上,这意味着无论 callable 返回什么值,图像都将上传到该路径。

例子:

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 中有更多信息还有一个例子,尽管与我上面发布的相似。