php - 将文件从 Android 上传到 DJango。 Request.FILES 总是空的

标签 php android python django

我正在尝试在我的 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.FILESrequest.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 was POST and the <form> that posted the request has the attribute enctype="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/

相关文章:

php - 使用 ACF Pro 在 WordPress 管理中为帖子列表选择字段可排序自定义列

android - 如何在textview android中为文本添加边框

android - 从 Android 缓慢上传文件到 Amazon S3

python - numpy.sum() 在大数组上给出奇怪的结果

PHP MySQL INNER JOIN 在第一个周期后停止工作

php - 多个表多列连接到同一个表

android - 保持 ListView 选择颜色

python - 在 Alpine Linux 上安装 Pillow 时没有这样的文件或目录 "limits.h"

python - 使用 Pandas 转换时间序列数组中包含周期的数据帧

php - getimagesize() 不适用于大图像 (640k+)