我正在开发一个与 Django 后端交互的 Android 应用程序。我已经使用 mod_wsgi 部署了 Web 服务,并且有许多 Web 服务调用可以工作并且已经过测试,所以我知道一切都应该工作。所有其他呼叫都工作正常。这是我在Android中调用的发送照片的方法。
public static String uploadFile(String url, int server_id, String filepath) {
try {
client.getParams().setParameter("http.socket.timeout", 90000); // 90 second
HttpPost post = new HttpPost(url);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("image", new FileBody(new File(filepath), "image/jpeg"));
post.setEntity(mpEntity);
post.addHeader("server_id", String.valueOf(server_id));
HttpResponse response = Connector.client.execute(post);
if (response.getStatusLine().getStatusCode() != 200) { return "false"; }
return convertStreamToString(response.getEntity().getContent());
} catch (Exception e) {
if (Constants.DEBUG) e.printStackTrace();
return "false";
}
}
这是我在views.py 文件中使用的接收和处理图像的方法:
@csrf_exempt
def incident_upload(request):
if request.method == 'POST':
server_id = request.POST['server_id']
incident = get_object_or_404(Incident, pk=server_id)
imagePath = '/Library/WebServer/program/uploads/' + str(int(time.time() * 1000)) + '.jpg'
destination = open(imagePath, 'wb+')
for chunk in request.FILES['image'].chunks():
destination.write(chunk)
destination.close()
incident.ImagePath = imagePath
incident.save()
return render_to_response('webservice/incident_read.html', {'incident': incident, 'device': incident.device})
当我尝试这种方法时,我得到了非常有用的 Apache 错误 500 内部服务器错误,但我不知道发生了什么。我知道这个方法有效,因为我可以使用我编写的自定义 html 页面来访问 Web 服务,而无需 Android,并且它工作得很好:
<html>
<body>
<form action="http://xxxxxxxxxxx.local/hermes/incident/upload/" enctype="multipart/form-data" method="post">
server_id: <input type="text" name="server_id" />
<br />
file: <input type="file" name="image" />
<br />
<input type="submit" value="send" />
</form>
</body>
</html>
所以我认为我在 Android 端格式化呼叫的方式一定有问题。我会提供错误日志或堆栈跟踪,但没有。我正在查看我的 apache 错误日志,但没有显示任何内容。有人有什么建议吗?
EDIT:
因此,我设置了 django 日志记录,并且当我从手机上点击它时,能够调试我的上传方法。当我说 server_id = request.POST['server_id'] 时,它似乎停止工作,所以不知何故,当我在 uploadFile 方法中发出请求时,该数据没有正确设置。有人看到我如何错误地执行请求吗?