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

Copy file into another folder with django?

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

通过查看 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')

注意:代码未经测试。

您可以将可调用对象传递给 upload_to。基本上,它的意思是可调用 returns 的任何值,图像都将在该路径中上传。

示例:

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 中有更多信息和示例,尽管与我上面发布的内容类似。

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