class FileStoreView(APIView):
@staticmethod
def read_file(url, chunk_size=512):
with open(url, "rb") as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
def get(self, request, *args, **kwargs):
dir_path = os.getcwd() + '/oos_file/{}'.format(self.request.query_params.get('dir_path'))
if dir_path.split("/")[-1].split(".")[-1] in ['jpg', 'png']:
with open(dir_path, 'rb') as f:
image_data = f.read()
return HttpResponse(image_data, content_type="image/png")
elif dir_path.split("/")[-1].split(".")[-1] == "mp4":
with open(dir_path, 'rb') as f:
image_data = f.read()
return HttpResponse(image_data, content_type="video/mp4")
elif dir_path.split("/")[-1].split(".")[-1] == "avi":
with open(dir_path, 'rb') as f:
image_data = f.read()
return HttpResponse(image_data, content_type="video/avi")
response = StreamingHttpResponse(self.read_file(dir_path))
response["Content-Type"] = "application/octet-stream"
response["Content-Disposition"] = 'attachment; filename={0}'.format(dir_path.split("/")[-1])
response["Access-Control-Expose-Headers"] = "Content-Disposition"
return response
@staticmethod
def post(request, *args, **kwargs):
file = request.FILES.get('file')
if not file:
raise exceptions.ParseError("空文件?")
uuid_str = int(time.time())
dir_path = os.getcwd() + '/oos_file/{0}.{1}'.format(uuid_str, file.name.split(".")[-1])
with open(dir_path, 'wb+') as f:
for line in file.chunks():
f.write(line)
return Response("/api/user/file_suffix/{0}.{1}".format(uuid_str, file.name.split(".")[-1]))