[英]Django - edit uploaded file Before final saving
我正在制作一個用於上傳和處理文件(主要是圖像,還有其他東西)的網站。 有時,某些文件在保存之前需要進行一些編輯。 我想在將上傳的文件保存到媒體目錄之前對其進行編輯(主要是為了避免 IO 交互,並且只將原始文件保留在 memory 中並在保存編輯版本后丟棄)。
編輯:所以我想我必須在 POST 中運行編輯 function,並更改 request.FILES 中的信息。 但我失敗了,不知道該怎么辦了。
注意:我主要是通過 class 視圖尋找一種方法。
這里有一些代碼供參考:
model:
class FilePatient(models.Model):
file_imag = models.FileField(upload_to='')
風景:
class FileAddView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, CreateView):
model = FilePatient
fields = ['file_imag']
def post(self, request, *args, **kwargs):
if request.FILES['file_imag'].name.endswith('.png'):
newFile=editFile(request.FILES['image_imag'])
# what to do, what not to do
return super().post(request, *args, **kwargs)
我希望以下內容對您有所幫助...如果原始文件太大,此代碼會通過調整原始文件的大小來“編輯”文件。 根據工作代碼,我替換了您在問題中使用的變量,未進行如下測試。
from pathlib import Path
import PIL
from six import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
img = request.FILES['fileInput']
if img.name.endswith('.png'):
fp = FilePatient.objects.get(...) # get the object for uploading file
img2 = PIL.Image.open(img)
exif = img2.info['exif'] if 'exif' in img2.info else None
max_hw = 800 # px width / height maximum
width_percent = (max_hw/float(img2.size[0]))
heigth_percent = (max_hw/float(img2.size[1]))
min_wh_percent = float(min(width_percent, heigth_percent))
if min_wh_percent <= 1:
width_size = int((float(img2.size[0])*min_wh_percent))
height_size = int((float(img2.size[1])*min_wh_percent))
img2 = img2.resize((width_size, height_size), PIL.Image.ANTIALIAS)
fp.file_imag = img2
buffer = BytesIO()
if exif:
img2.save(buffer, format='JPEG', exif=exif, quality=90)
else:
img2.save(buffer, format='JPEG', quality=90)
buffer.seek(0)
fp.file_imag.name = Path(img.name).stem
fp.file_imag = InMemoryUploadedFile(buffer,
'ImageField',
f"{fp.file_imag.name}.jpg",
'image/jpeg',
img2.size,
"utf-8")
fp.save()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.