python - 使用 Django 传递文件对象

标签 python django parse-platform

我正在尝试检索文件,然后通过 POST 提交将其上传到 Parse.com。我的 HTML:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="container">
   <form action="" id="fileupload" name="fileupload" enctype="multipart/form-data" method="post">
   {% csrf_token %}
     <fieldset>
       <input type="file" name="fileselect" id="fileselect" /></input>
       <input type="hidden" name="myFile" id="myFile" />
       <input id="uploadbutton" type="submit" value="Upload to Parse" />
     </fieldset>
   </form>
</div>

并使用以下函数来检索文件:

<script type="text/javascript">
  $(function() {
    var file;

    // Set an event listener on the Choose File field.
    $('#fileselect').bind("change", function(e) {
      var files = e.target.files || e.dataTransfer.files;
      // Our file var now holds the selected file
      file = files[0];
      document.getElementById('myFile').value = file;
    });
  });
</script>

但是,这个“myFile”字段不会将文件作为对象发布,也不会与 Parse API 文档一致,该文档似乎正在寻找文件路径名,我认为我无法从未知机器。

import json,httplib
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('POST', '/1/files/pic.jpg', open('myPicture.jpg','rb').read(), {
   "X-Parse-Application-Id": "xxxxxxxxxxxxxxxxxxxxx",
   "X-Parse-REST-API-Key": "xxxxxxxxxxxxxxxxxxxxxxx",
   "Content-Type": "image/jpeg"
 })
result = json.loads(connection.getresponse().read())
print result

这似乎是一个常见的用例,但我找到的唯一文档是针对 ajax 的,我不想使用它,因为它公开了我的 API 凭据 https://www.parse.com/questions/uploading-files-to-parse-using-javascript-and-the-rest-api .

我不确定处理该文件的最佳方法是什么...是否有在 Django 框架内处理的方法或者我是否需要转换为 JSON。而且,即使捕获了文件对象,我也不清楚如何将 Parse.com API 与文件对象一起使用。

最佳答案

经过一番研究,结果发现答案非常简单。使用 Django 网站上的“基本文件上传”文档:https://docs.djangoproject.com/en/1.8/topics/http/file-uploads/并替换

open('myPicture.jpg', 'rb').read()

在 Parse 文档中(在上面的问题中引用)与

request.FILES['file']

我能够成功地将文件上传到 Parse。无需 JavaScript。

关于python - 使用 Django 传递文件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33352019/

相关文章:

python - 如何将 Python RQ Worker 连接到 unix 套接字上的 redis 服务器?

python - BucketIterator 抛出 'Field' 对象没有属性 'vocab'

python - 如何在 Django 中获取对象作为字符串?

Android 解析推送通知和新的 GCM 生成错误的设备 token 并解析推送通知不起作用

python - Gunicorn 通过导致 404 导致 Flask 的 add_url_rule

Javascript不会在django的表单集隐藏输入字段中插入值

python - 用 celery 运行 "unique"任务

java - 无法使用 JAVA 中的 parse4j API 在 Parse.com 中插入对象

ios - Parse.com - 查询自定义类中的关系

python - 从 python 中的 list.remove() 获取修改后的列表