[英]how to handle a media file without save it in django
在我的django项目中,我收到了客户端发布的媒体文件。 像这样
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'], request.POST['fid'])
return JsonResponse({"result":"ok"})
return JsonResponse({"result":"failed","msg":"unkown"})
def handle_uploaded_file(f, fid):
with open(STEP_DIR + '/' + fid, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
另一方面,我想通过另一个模块来处理此文件。 然后此模块将打开一个文件并按以下方式处理它:
Import thirdModule
thirdModule.open('path_to_url').exporter(...)
由于thirdModule将通过给定路径打开文件。 所以我必须保存刚刚从django收到的文件?
有什么办法可以直接处理文件而不保存它?
def handle_uploaded_file(f, fid):
thirdModule.open(convert_media_to_stream(f))
...
if form.is_valid():
data = form.cleaned_data
inmemory_uploaded_file = data['file_field_name']
file_name = str(inmemory_uploaded_file)
process_file_without_saving_into_disk(inmemory_uploaded_file)
# rest of your code
更新资料
def handle_upload(file, file_name, upload_path):
if not os.path.exists(upload_path):
os.mkdir(upload_path)
file_path = os.path.join(upload_path, file_name)
with open(file_path, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
return file_path
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.