繁体   English   中英

使用Android上传文件到Django Web服务

[英]Upload a file with Android to Django web service

我正在开发一个与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页面来点击没有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方法中发出请求时,这段数据没有正确设置。 有人看到我正在做错的请求吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM