我正在尝试在我的 Android 应用程序中使用以下代码将文件上传到 Django:
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(screenshotFile), -1);
reqEntity.setContentType("application/octet-stream");
reqEntity.setChunked(true);
HttpPost httpPost = new HttpPost(serverAddress);
httpPost.setEntity(reqEntity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
我发现很多帖子都说之前的代码可以在其他服务器上运行,比如 PHP,但是由于某种原因,request.FILES
字典是空的,因此,我什么也做不了与上传的文件。下一个方法帮助我检查 request.FILES
和 request.POST
中的值(也是空的)
以下
@csrf_exempt
def upload_file(request):
print request.FILES
print request.POST
return HttpResponse("")
我还尝试用 FileEntity reqEntity = new FileEntity(screenshotFile, "application/octet -stream")
-如其他答案所述 - 但同样的事情发生了。
可能我应该在别处而不是在 request.FILES
中寻找。有没有人知道如何解决这个问题?
编辑
我已经测试过 MultipartEntityBuilder
,它可以工作,但这意味着要向项目添加额外的 jars*,我宁愿不这样做。
最佳答案
来自 Django documentation :
Note that
request.FILES
will only contain data if the request method wasPOST
and the<form>
that posted the request has the attributeenctype="multipart/form-data"
. Otherwise,request.FILES
will be empty.
当你在发送数据时,Django 可能会在request.BODY
中找到内容。而不是 request.FILES
.
所以你必须使用 MultipartEntityBuilder
或手动设置您的请求(例如通过操作 header )以便 Django 将其识别为 multipart/form-data
,但我不能告诉你这会起作用。
关于php - 将文件从 Android 上传到 DJango。 Request.FILES 总是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34273056/