models.py
class FileUpload(models.Model):
File_Name = models.CharField(max_length=255, blank=True)
File_path = models.FileField(upload_to='')
Description = models.CharField(max_length=255, blank=True)
Upload_Date = models.DateTimeField(auto_now_add=True)
forms.py
class FileUploadForm(forms.Form):
class Meta:
model = FileUpload
File_Name = forms.CharField(label="File Name",max_length=255)
Description = forms.CharField(label="Description", max_length=255)
我是Django的新手,我需要帮助。如何在数据库中上传图像并查看这些图像?预先感谢!
此处,路径存储在数据库中,图像存储在文件夹中。但是我不需要。我想保存图像和数据库路径,我需要查看该图像。请帮忙!
views.py:
def uploadfile(request):
print('inside upload logic')
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
# ImageUpload(request.FILES['File_Name'])
myfile = request.FILES['File_Name']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
newdoc = FileUpload(File_Name=myfile.name, File_path=uploaded_file_url, Description=request.POST['Description'])
newdoc.save()
#return HttpResponse("File uploaded successfuly")
return render(request, 'Login/fileupload.html')
else:
form = FileUploadForm()
return render(request, 'Login/fileupload.html', {
'form': form
})
答案 0 :(得分:0)
通常不应将图像数据存储在数据库中。如果您需要上传和存储图像,请使用ImageField
或FileField
并按照docs中的说明保存图像。您唯一需要做的是:
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
uploaded_file = FileUpload(
File_path=request.FILES['File_path'], # or whatever you've called the file input
File_name=form.cleaned_data['File_Name'],
Description=form.cleaned_data['Description'])
uploaded_file.save()
在您的情况下使用ModelForm
会更容易,那么您只需要保存以下表单:
if form.is_valid():
form.save()
这将以正确的方式自动保存文件。无需像您一样手动进行保存。
查看图像非常简单:
file_upload = FileUpload.objects.get(id=34)
file_url = file_upload.File_path.url # url relative to `MEDIA_ROOT`
# or in a template
{% load static %}
{% get_media_prefix %}{{ file_upload.File_path.url }}
如果您确实需要将图像作为二进制Blob存储到数据库中(但是请注意,这样做几乎没有任何意义),请使用Django的BinaryField
,如here所述。
这也意味着您将不得不处理将图像从二进制Blob来回转换为正确的图像文件的过程。考虑还存储内容类型(image / jpg或image / png或image / webp),因为您将需要正确地重新创建文件。