2011-12-09 84 views
6

我正在开发一个与Django后端接口的Android应用程序。我已经使用mod_wsgi部署了webservice,并且有很多web服务调用可以工作并且已经过测试,所以我知道所有的东西都应该可以工作。所有其他通话都可以正常工作。这是我在Android中拨打照片的方法。使用Android将文件上传到Django Web服务

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方法中发出请求时,那部分数据没有正确设置。任何人都看到我不正确地处理请求?

+0

Apache错误日志说什么? –

+0

没什么!大声笑它没有任何帮助!当我设置mod_wsgi时,它有错误,我可以找到并修复,但没有显示这个错误 – Josh

+0

我在想也许这个问题可能与你的内容类型头,但你发送一个表单。 –

回答

2

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

相关问题