在Django中将文件复制到另一个文件夹?

3
我需要在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')
3个回答

3
你可以将可调用对象传递给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)

文档中有更多信息和一个示例,虽然与我上面发布的内容相似。


2
通过查看Django文档,当你执行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')

注意:代码未经测试。

0
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage



def uploadimage(request):
    if request.method == 'POST' and request.FILES['avatar']:
        img = request.FILES['avatar']
        fs = FileSystemStorage()

        #To copy image to the base folder 
        #filename = fs.save(img.name, img)     

        #To save in a specified folder
        filename = fs.save('static/profile/'+img.name, img)
        uploaded_file_url = fs.url(filename)                 #To get the file`s url
        return render(request, 'myapp/upload.html', {
            'uploaded_file_url': uploaded_file_url
        })
     return render(request, 'myapp/upload.html')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接