【问题标题】:Upload a file with Android to Django web service使用 Android 将文件上传到 Django Web 服务
【发布时间】:2012-01-16 20:27:13
【问题描述】:

我正在开发一个与 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 Internal Server Error,我不知道发生了什么。我知道这种方法有效,因为我可以使用我编写的自定义 html 页面在没有 Android 的情况下访问 Web 服务,并且效果很好:

<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 错误日志,但没有任何显示。有人有什么建议吗?

编辑: 因此,我设置了 django 日志记录,并且当我通过手机点击它时,我已经能够调试我的上传方法。当我说 server_id = request.POST ['server_id'] 时,它似乎停止工作,所以不知何故,当我在 uploadFile 方法中发出请求时,该数据没有正确设置。有人看到我如何错误地执行请求吗?

【问题讨论】:

  • Apache 错误日志是怎么说的?
  • 没什么!大声笑这根本没有帮助!当我设置 mod_wsgi 时,它有我可以找到并修复的错误,但没有显示此错误
  • 我在想问题可能出在您的内容类型标头上,但您正在发送表单。
  • 是的,我真的不知道如何解决它。就像我说的,令人沮丧的是我没有任何错误可以解决。

标签: android django file-upload


【解决方案1】:

我发现我做错了什么。设置 django 日志记录后,我能够看到它崩溃的位置。当我试图检索“server_id”变量时它崩溃了。我最终将该变量作为字符串主体添加到多部分实体中,而不是将其设置为标题。

【讨论】:

    猜你喜欢
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多