[英]Corrupted Image upload from Django
這是我用於上傳在基於類的視圖中定義的圖像的代碼,
def _handle_uploaded_file(self, request):
folder = settings.MEDIA_ROOT
uploaded_filename = request.FILES['img_fl'].name
BASE_PATH ='/home/admin1/Desktop/virtualenv-12.1.1/mapfied'
# create the folder if it doesn't exist.
try:
os.mkdir(os.path.join(BASE_PATH, folder))
except Exception as e:
pass
# save the uploaded file inside that folder.
full_filename = os.path.join(BASE_PATH, folder, uploaded_filename)
fd = open(full_filename, 'wb')
file_content = ContentFile( request.FILES['img_fl'].read() )
try:
for chunk in file_content.chunks():
fout.write(chunk)
fout.close()
html = "<html><body>SAVED</body></html>"
print(html)
except Exception as e:
print(e)
圖片文件已保存到名稱正確的位置,但已損壞。我找不到確切的原因,我在這里做錯了嗎?
這是我以前的項目中用於將上傳文件寫入磁盤的內容:
def view_handling_function(request):
for key, value in request.FILES.iteritems():
full_path = ...
save_uploadfile_to_disk(full_path, value)
def save_uploadfile_to_disk(full_path, file):
with open(full_path, 'w+') as destination:
for chunk in file.chunks():
destination.write(chunk)
我認為,由於您要編寫二進制上傳文件,因此需要使用可寫二進制模式(實際上是wb +)打開文件。
您也可以使用'with'關鍵字來整理一下; 在這里查看Django示例。
旁注:如果將文件作為FileField(或派生類)持久化,則可以提供“ upload_to”函數,該函數返回要在其中存儲文件的完整路徑和文件名。 這將使框架為您處理文件io。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.