我正在使用一个简单的 REST 客户端进行测试。发送一个简单的 JPEG,尝试了以下内容类型: 内容类型:图像/jpeg 内容类型:多部分/表单数据
另请注意,csrftoken 身份验证已关闭以允许外部第 3 方 REST 连接。
(图像通过其余客户端附加) 检查了wireshark,并根据上述参数设置了数据包。
Django - 请求对象有几个变量: 请求体 请求.FILES
Django 服务器接收到 POST 后,请求对象始终将所有数据/有效负载存储到 request.body 中。图像或任何附加文件不应该进入 request.FILES 吗?内容类型或 POST 是否设置不正确。
非常简单的代码。只是想打印到日志中。 post中的所有对象都继续到request.body
def testPost(request):
print request.body
print request.FILES
return HttpResponse()
Wireshark 数据包:
Hypertext Transfer Protocol
POST /testPost/ HTTP/1.1\r\n
Host: MYURL.com:8000\r\n
Connection: keep-alive\r\n
Content-Length: 8318\r\n
Origin: chrome-extension://aejoelaoggembcahagimdiliamlcdmfm\r\n
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36\r\n
Content-Type: image/jpeg\r\n
Accept: */*\r\n
Accept-Encoding: gzip,deflate,sdch\r\n
Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4\r\n
Cookie: ******; csrftoken=**********\r\n
\r\n
[Full request URI: http://MYURL.com:8000/testPost/]
[HTTP request 1/1]
JPEG 文件交换格式
最佳答案
以下是我处理文件上传的方式:在本例中恰好是图像。我一直在努力解决的问题之一是该请求。FILES 可能带有多个 key ,而我一直想要最后一个。
注意:request.FILES 仅在以下情况下包含数据:
- 请求是一个POST
- 请求具有属性 'enctype="multipart/form-data"'
参见 Django File-uploads文档以获取更多详细信息。
模型:首先有一个带有 ImageField 的模型:models.py
photos_dir = settings.MEDIA_ROOT + "/photos" + "/%Y/%m/%d/"
class Photo(models.Model):
image = models.ImageField(upload_to=photos_dir, null=True, blank=True, default=None)
filename = models.CharField(max_length=60, blank=True, null=True)
View : 在 views.py 中处理帖子:
from django.core.files.images import ImageFile
def upload_image( request ):
file_key=None
for file_key in sorted(request.FILES):
pass
wrapped_file = ImageFile(request.FILES[file_key])
filename = wrapped_file.name
# new photo table-row
photo = Photo()
photo.filename = filename
photo.image = request.FILES[file_key]
try:
photo.save()
except OSError:
print "Deal with this situation"
# do your stuff here.
return HttpResponse("boo", "text/html");
The Standlone Poster:一些 python 代码来刺激你的 django View 。
引用:我实际上使用了这个库:poster.encode将数据“刺激”到我的 django view.py
from poster.streaminghttp import register_openers
from poster.encode import multipart_encode
import urllib2
server = "http://localhost/"
headers = {}
# Register the streaming http handlers with urllib2
register_openers()
img="path/to/image/image.png"
data = {'media' : open( img ),
'additionalattr': 111,
}
datagen, headers = multipart_encode(data)
headers['Connection']='keep-alive'
request = urllib2.Request('%s/upload_image/' % ( server ), datagen, headers)
print urllib2.urlopen(request).read()
关于django - 通过 POST 发送文件,Django/python 请求对象存储不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20928278/