Skip to main content
 首页 » 编程设计

python之从 Django 中的 Imagefield 上传图像

2024年10月25日31hnrainll

我是 Django 的新手。我的 html 文件中有以下代码:

{% load staticfiles %} 
<form method="post"> {% csrf_token %} 
<input type="file" name="file"> 
<button>Submit</button> 
</form> 
{{file}} 
<img class="hl" src="{{ MEDIA_URL }}photos/abc.png" /></a> 
<img class="hl" src="{% static 'blog/images/sec.png' %}" /></a> 

上面代码的views.py是:

if request.method == 'POST': 
        if 'file' in request.POST: 
            f = request.POST['file'] 
            a = MyUser(email="frt@wer.com", date_of_birth=date.today()) 
            a.photo.save('somename.png', File(open(f, 'r'))) 
            a.save() 
            context = {'file': f} 
            return render(request, 'home.html', context) 

现在浏览器不会从用户本地设备返回文件的绝对路径,它只是收集文件名,因为一些安全问题但是a.photo.save('somename.png', File(open(f, 'r'))) 这部分代码需要用户本地设备的绝对路径,类似于 /home/abc/Pictures/sec.png all我得到的是 sec.png,因此我无法上传。

来自 python manage.py shell:

>>>a = MyUser(email="frt@wer.com", date_of_birth=date.today()) 
>>>a.photo.save('somename.png', File(open('/home/abc/Pictures/sec.png', 'r'))) 
>>>a.save() 

这很好用。有没有一些解决方法。我不想使用 Form。

请您参考如下方法:

如果您想允许文件上传,我建议您使用文件表单而不是变通方法。可以在此处找到一个简单且非常简洁的示例:

Need a minimal Django file upload example