我正在使用Tastypie编写API,我想上传包含多部分http请求的文件。
我在我的android文件中的异步任务中创建了这个函数:
public JSONObject getJSONObejctPOSTFILE(String url,
List<NameValuePair> params, String key) {
HttpClient client = HttpClientFactory.getThreadSafeClient();
HttpPost requestPOST = new HttpPost("http://192.168.0.194/api/v1/newresource/?format=json");
//the request is definied
requestPOST.setHeader("Content-type", "multipart/form-data");
requestPOST.setHeader("Accept", "application/json");
try {
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("name", new StringBody("new.jpg"));
multipartEntity.addPart("type", new StringBody("image"));
File image = new File(DataObjectToNet.getList_objects().get(0).getData());
FileBody fil = new FileBody(image);
multipartEntity.addPart("file", new FileBody(image));
requestPOST.setEntity(multipartEntity);
client.execute(requestPOST, new PhotoUploadResponseHandler());
} catch (Exception e) {
System.out.println(e.toString());
}
return null;
}
tastypie中的api是访问https://github.com/toastdriven/django-tastypie/issues/42中生成的代码。问题是当我用android客户端发送文件时,服务器给我下一个响应:
{"error_message": "Invalid boundary in multipart: None", "traceback": "Traceback (most recent call last):\n\n File \"/usr/lib/python2.7/site-packages/tastypie/resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"/usr/lib/python2.7/site-packages/tastypie/resources.py\", line 397, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"/usr/lib/python2.7/site-packages/tastypie/resources.py\", line 427, in dispatch\n response = method(request, **kwargs)\n\n File \"/usr/lib/python2.7/site-packages/tastypie/resources.py\", line 1161, in post_list\n deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))\n\n File \"/var/www/html/patit_server_app/api/api.py\", line 346, in deserialize\n data = request.POST.copy()\n\n File \"/usr/lib/python2.7/site-packages/django/core/handlers/modpython.py\", line 69, in _get_post\n self._load_post_and_files()\n\n File \"/usr/lib/python2.7/site-packages/django/http/__init__.py\", line 360, in _load_post_and_files\n self._post, self._files = self.parse_file_upload(self.META, data)\n\n File \"/usr/lib/python2.7/site-packages/django/http/__init__.py\", line 319, in parse_file_upload\n parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)\n\n File \"/usr/lib/python2.7/site-packages/django/http/multipartparser.py\", line 65, in __init__\n raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary)\n\nMultiPartParserError: Invalid boundary in multipart: None\n"}
知道这是问题吗? android http请求它是床格式吗?我知道tastypie将文件上传到我的服务器是一种糟糕的方式,但我想在这种形式下这样做。
Tastypie API是:
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)
class ResourceNewResource(MultipartResource,ModelResource):
fil = Base64FileField('data')
class Meta:
queryset = res.objects.all()
resource_name = 'newresource'
serializer = Serializer(formats=['json'])
allowed_methods = ['get','post']
always_return_data=True
authorization = Authorization()
有人可以帮我上传android文件到tastypie django服务器吗?
谢谢!!!
答案 0 :(得分:0)
我终于可以上传文件,但我没有使用tastypie API。我利用Django文件上传。上传我使用的文件的代码是:
def upload_file(request):
if request.method == 'POST':
print "file"
new_file = Resource(name=request.FILES['file'].name,data=request.FILES['file'],type = "ARCHIVE",create_date=timezone.now(), route=settings.MEDIA_ROOT)
new_file.save()
response_data={result":"OK"}
return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
else:
response_data={"success": "No a post request"}
return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')