简体   繁体   English

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

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

I'm working on an Android app that interfaces with a Django backend. 我正在开发一个与Django后端接口的Android应用程序。 I've deployed the webservice using mod_wsgi, and have many web service calls that work and have been tested, so I know everything SHOULD be working. 我已经使用mod_wsgi部署了web服务,并且有许多Web服务调用可以工作并且已经过测试,因此我知道一切都应该正常工作。 All the other calls work fine. 所有其他调用工作正常。 This is the method I call in Android to send the photo. 这是我在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";
    }
}

This is the method I'm using in my views.py file to receive and process the image: 这是我在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})

When I try this method, I get the really helpful Apache error 500 Internal Server Error, and I have no clue what's going on. 当我尝试这种方法时,我得到了真正有用的Apache错误500内部服务器错误,我不知道发生了什么。 I know this method works because I can use a custom html page I wrote to hit the web service without Android and it works fine: 我知道这个方法有效,因为我可以使用我编写的自定义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>

So I think there has to be something wrong with how I'm formatting the call on the Android side. 所以我认为我在Android方面格式化调用的方式有问题。 I'd provide an error log or stack trace but there aren't any. 我提供错误日志或堆栈跟踪,但没有。 I'm looking at my apache error log and nothing shows up. 我正在查看我的apache错误日志,没有显示任何内容。 Anyone have any advice? 有人有什么建议吗?

EDIT : So I set up django logging and have been able to debug my upload method when I hit it from the phone. 编辑 :所以我设置了django日志记录,并且当我从手机上点击它时能够调试我的上传方法。 It seems it stops working when I say server_id = request.POST['server_id'], so somehow, that piece of data isn't getting set right when I make the request in the uploadFile method. 当我说server_id = request.POST ['server_id']时,它似乎停止工作,所以不知何故,当我在uploadFile方法中发出请求时,这段数据没有正确设置。 Anyone see how I'm doing the request incorrectly? 有人看到我正在做错的请求吗?

I figured out what I was doing wrong. 我弄清楚我做错了什么。 After setting up django logging, I was able to see where it was crashing. 设置django日志后,我能够看到崩溃的位置。 It was crashing when I tried to retrieve the "server_id" variable. 当我试图检索“server_id”变量时它崩溃了。 I ended up adding that variable to the multipart entity as a string body rather than setting it as a header. 我最终将该变量作为字符串体添加到multipart实体,而不是将其设置为标题。

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

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