如何在不将用户重定向到服务器的情况下将django中的文件发送到其他服务器?所以在django中重写这个简单的php函数:
$filename = 'C:/tmp/myphoto.jpg';
$handler = 'http://www.example.com/upload.php';
$field = 'image';
$res = send_file($filename, $handler, $field);
if ($res) {
echo 'done.';
} else {
echo 'something went wrong.';
}
第二台服务器上的功能只是简单的php func,它从$_FILES
读取文件:
<?php
move_uploaded_file(
$_FILES['image']['tmp_name'],
'/var/www/image/uploaded-file.jpg'
);
echo 'file saved.';
?>
我已经尝试了django-filetransfers,但它确实有效,但我无法让它停留在我上传文件的页面上。我已经编辑了upload_handler视图并正确发送了文件,但之后我被重定向到我的第二台服务器:
def upload_handler(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect("/upload")
upload_url, upload_data = prepare_upload(request, "address of my server/")
form = UploadForm()
return direct_to_template(request, '/upload.html',
{'form': form, 'upload_url': upload_url, 'upload_data': upload_data,
'uploads': UploadModel.objects.all()})
这是我的方法。我正在使用来自httplib的函数以及来自python-poster的multipart_encode函数,它创建了我的文件头:
def file_upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
f = request.FILES['file']
logging.debug(f)
status = send_file(request.FILES['file'])
c = RequestContext(request, {
"status" : status,
})
template = "management/status.html"
result = render_to_string(template, c)
return HttpResponse(result)
else:
form = UploadFileForm()
return render_to_response('management/file_upload.html', {'form': form})
def send_file(file):
datagen, headers = multipart_encode({"myfile": file})
conn = httplib.HTTPConnection(HOST)
conn.request('POST', '/rte/', file, headers)
res = conn.getresponse()
if res.status != 200:
logging.debug("error \n")
logging.debug(file)
logging.debug("\n")
logging.debug(headers)
return res.status
HTML:
<form action="{{ views.file_upload }}" method="POST" enctype="multipart/form-data">
{{ form.as_p }}
<input type="submit" value="Upload" />
</form>
结果我得到'错误500'并在调试中:
2010-10-20 18:12:55,819 DEBUG thumb.php4.jpg
2010-10-20 18:14:55,968 DEBUG error
2010-10-20 18:14:55,968 DEBUG thumb.php4.jpg
2010-10-20 18:14:55,969 DEBUG
2010-10-20 18:14:55,969 DEBUG {'Content-Length': 15019, 'Content-Type': 'multipart/form-data; boundary=02cafbc1d080471284be55dc1095b399'}
我的功能基于python / django文档和我在互联网上找到的一些解决方案。功能看起来相同但不知何故它不起作用。我应该采取不同的方法吗?在php中我不需要定义标题等。