2
文件管理器
我想上傳任何文件,我有一個文件管理器服務,獲取文件和保存沒有擴展名和文件名是UUID和返回文件信息。如何找到該文件是圖像或文檔或...沒有擴展名和內容類型?
我的文件管理器的處理程序:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from pyramid_storage.exceptions import FileNotAllowed
import uuid
from pyramid.view import view_config
from pyramid.response import Response
import os
class UploadHandler:
def __init__(self, request):
self.request = request
self.settings = self.request.registry.settings
@view_config(route_name='upload', request_method='POST', renderer='json')
def post(self):
# file
f = self.request.POST.items()
# file name
file_name_main = f[0][1].filename
# content type
content_type = str(f[0][1].type)
if content_type:
extension_main = content_type.split('.')[-1]
# set id for file name
if extension_main:
f[0][1].filename = str(uuid.uuid4())
else:
response = Response(body=json.dumps({'ERROR': 'Your File Not Allowed'}))
response.headers.update({
'Access-Control-Allow-Origin': self.settings['Access-Control-Allow-Origin'],
})
return response
else:
response = Response(body=json.dumps({'ERROR': 'Your File Not Allowed'}))
response.headers.update({
'Access-Control-Allow-Origin': self.settings['Access-Control-Allow-Origin'],
})
return response
try:
# save file
file_name = str(self.request.storage.save(f[0][1]))
except FileNotAllowed:
response = Response(body=json.dumps({'ERROR': 'Your File Not Allowed'}))
response.headers.update({
'Access-Control-Allow-Origin': self.settings['Access-Control-Allow-Origin'],
})
return response
# file name == file id
f_name = file_name
file_path = self.request.storage.base_path + os.sep + f_name
file_size = os.path.getsize(file_path)
response = Response(body=json.dumps(
{'file_id': f_name, 'file_name': file_name_main, 'content_type': content_type, 'size': file_size,
'extension': extension_main}))
response.headers.update({
'Access-Control-Allow-Origin': self.settings['Access-Control-Allow-Origin'],
})
return response
**例如:** 爲圖像I可以使用枕頭程序庫以檢測圖像: 從PIL進口Image' ' '嘗試:'' 與Image.open( 「m.jpg」)作爲im:' 'pass'' 'except exception,e:' 'print(「ERROR:FileNotAllowed」+ str(e))' – J4v4d