上传与Android文件到Django的Web服务 [英] Upload a file with Android to Django web service

查看:630
本文介绍了上传与Android文件到Django的Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的Andr​​oid应用程序,与Django的后端接口。我已经部署使用mod_wsgi的web服务,并有许多Web服务调用的工作和已经过测试,所以我知道一切都应该工作。所有其他电话正常工作。这是我在Android中调用发送照片的方法。

I'm working on an Android app that interfaces with a Django backend. 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. All the other calls work fine. This is the method I call in Android to send the photo.

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文件,接收和处理图像的方法:

This is the method I'm using in my views.py file to receive and process the image:

@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服务,它工作正常:

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. 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>
<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错误日志和什么也不显示。任何人有什么建议吗?

So I think there has to be something wrong with how I'm formatting the call on the Android side. 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. Anyone have any advice?

修改
所以,我成立了Django的日志记录,并已能够调试我上传的方法时,我打它从手机。这似乎停止,当我说SERVER_ID = request.POST ['SERVER_ID'],所以不知何故,该数据块是没有得到正确的设置,当我做了uploadFile方法的要求工作。任何人看到我是如何做正确的请求?

EDIT: So I set up django logging and have been able to debug my upload method when I hit it from the phone. 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. Anyone see how I'm doing the request incorrectly?

推荐答案

我想通了,我在做什么错。设立Django的记录后,我能看到它崩溃。它崩溃时,我试图找回SERVER_ID变量。最后我补充说,变量多部分实体作为字符串的身体,而不是将其设置为标题。

I figured out what I was doing wrong. After setting up django logging, I was able to see where it was crashing. It was crashing when I tried to retrieve the "server_id" variable. I ended up adding that variable to the multipart entity as a string body rather than setting it as a header.

这篇关于上传与Android文件到Django的Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆